Q: How do you update the DOM in React?

A: Call the setState() function on the component you want to update. setState() will re-render the virtual DOM, which will check for anything that has changed, and update the page display accordingly.

Interestingly enough, the state doesn't even have to change. For example, in the code snippet below, I have the status value initially set to 0, and in my handleClick() function I set the state (this.setState({ status: 0 });) to the same value of 0, which re-renders the component.

  class MainContainer extends React.Component 
{
  constructor(props) 
  {
    super();
    this.state = { status: 0};
  }
  handleClick() {
    recipes.push(<Recipe />);
    this.setState({ status: 0 });
  }
  render () 
  {
    return (
      <div id="accordion" role="tablist" aria-multiselectable="true">
        {recipes}
        <button onClick={() => this.handleClick()} className="btn btn-primary">Add</button>
      </div>
    );
  }
}

ReactDOM.render(
<MainContainer />,
document.getElementById('app'));


451 0 6