Use State to Toggle an Element ** toggle method without if statement

Tell us what’s happening:
I would like to know why this doesn’t work

toggleVisibility() {
    this.setState({
      visibility : !this.visibility
    })
  } 

it should negate the boolean state upon each call to the method

Your code so far


class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };
    // change code below this line
    this.toggleVisibility = this.toggleVisibility.bind(this);
    // change code above this line
  }
  // change code below this line
  toggleVisibility() {
    this.setState({
      visibility : !this.visibility
    })
  }
  // change code above this line
  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_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.

Link to the challenge:

Remember that visibility is stored inside your state object.

1 Like

thanks a lot !! this works: visibility : !this.state.visibility