React - Use State to Toggle an Element

Why we have to use { } ? can’t we directly use JavaScript in here

Your code so far

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };
    this.toggleVisibility = this.toggleVisibility.bind(this);
  }
  toggleVisibility() {
    this.setState(state => {
      if (state.visibility === true) {
         return { visibility: false };
       } else {
         return { visibility: true };
      }
    });
  }
    
  render() {
    if (this.state.visibility) {
      return (
        <div>
          <button onClick={this.toggleVisibility}>Click Me</button>
          <h1>Now you see me!</h1>
        </div>
      );
    } else {
      return (
        <div>
          <button onClick={this.toggleVisibility}>Click Me</button>
        </div>
      );
    }
  }
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: React - Use State to Toggle an Element

Link to the challenge:

1 Like

I am not sure what the ask is but the reason you have to use state and not use JavaScript directly is that React uses a virtual DOM, if you mutate the value directly, the component would not re-render and React would not be aware of the changes as it’s now technically ‘beyond’ the reach of React to keep track of the value.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.