Help with setState()

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(state => {
      if (state.visibility === true) {
        return {visibility: false}
      }
      else {
        return {visibility: true}
      }
    })}
  // 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>
      );
    }
  }
};

Why does this code work when we are not passing in a specific state into toggleVisibility we are only calling {this.toggleVisibility}

You are passing a specific state: the current state of MyComponent. When you pass a function to the setState method, the argument passed to the function is the current state of the component.

Ohhh ok, but howcome you do this:

{
        return {visibility: false}
      }

instead of

return {this.state.visibility : false}

Im confused how returning

{
        return {visibility: false}
      }

Changes it in the state

You should probably review how setState works. Review what you are supposed to return to change the values of a components state. Then, you should understand why you do not reference this.state.visibility.

1 Like