max_new
max_new

Reputation: 343

React not re-rendering on state change

I am rendering a new form when the button is clicked. So basically I change a state within the component from:

false to true or null to true

However, it is strange that component does not re-render after the state change

export default class BoardManager extends React.Component{
   constructor(){
    super();
    this.state = {
      newForm : null
    };
    setTimeout(() => {
      this.state = {
        newForm : true
      };
      console.log(this.state.newForm);
    },1000);
  }

  render(){
    return(
      <div>
        Some thing here
        {this.state.newForm ? <NewBoardForm />: null}
      </div>
    )
  }
} 

Help much appreciated!!!

Edit!!! Solution

export default class BoardManager extends React.Component{
  constructor(){
    super();
    this.state = {
      newForm : null
    };
  }

  render(){
    return(
      <div>
        <BoardsTable boards={BoardData.boards}/>
        <button onClick={() => {
            this.setState({
              newForm : true
            });
            console.log(this.state.newForm);
          }}>Add New</button>
          <button onClick={() => {
              this.setState({
                newForm : null
              });
              console.log(this.state.newForm);
            }}>Delete</button>
        {this.state.newForm ? <NewBoardForm />: null}
      </div>
    )
  }
}

Upvotes: 5

Views: 11905

Answers (3)

Youcef Chihi
Youcef Chihi

Reputation: 331

You can use this.forceUpdate() at the end of onClick. Reference: https://facebook.github.io/react/docs/component-api.html

Upvotes: -2

zachguo
zachguo

Reputation: 6716

You have to use this.setState({newForm: true}) instead of this.state = {newForm : true}

And put setState in other lifecycle stages.

Upvotes: 8

Samer Buna
Samer Buna

Reputation: 9311

Move the setTimeout call to inside a componentDidMount and use this.setState in there

Upvotes: 9

Related Questions