How does the method work?

Tell us what’s happening:
So I tried this on my own at first and I thought I had the answer, but it wasn’t passing. Then I watched a video and took a look at the solutions. My answer wasn’t far off, but I’m having trouble understanding this part:

toggleVisibility () {
this.setState(state => {
  if (state.visibility == true) {
    return {visibility: false}
  } else {
    return {visibility: true}
  }
} )
}

how do the return values know that visibility is referring to this.state in the constructor?

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(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>
    );
  }
}
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36.

Challenge: Use State to Toggle an Element

Link to the challenge:

Because the setState callback function takes the current state as an argument and returns the new state. The return values don’t “know” anything. If you pass a callback function to setState, the return value of that function is the new state that you’re setting.

1 Like

Okay so the setState is what connects the return {visibility: true} to the state object? I’m wanting to make sure I understand how it updates the visibility key for the state object as opposed to some other object that might have the same key. Maybe it’s a stupid question, but it’s not clicking for some reason.