Toggle react using bind method

Tell us what’s happening:
So I want to toggle the state using conditional, but it does not work. I’m sure the parameter on if false, and I don’t have any clue anymore.

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() {
  if (this.visibility == true){
    this.setState({
      visibility: false
    })
  } else {
    this.setState({
      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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36.

Challenge: Use State to Toggle an Element

Link to the challenge:

so I change the conditional parameter, it works. but the lesson didn’t pass
this.state.visibility == true

It is this line of code in the toggleVisibility:

if (this.visibility == true)

visibility can’t be accessed directly after this as it’s not a method of the constructor or a property it’s inside the state

your function could be like this:

toggleVisibility() {
        this.setState({
          visibility:  this.state.visibility ? false : true
    })
  }
}

I used ternary operators you can read more here mdn
Ternary operators are concise and cleaner than the traditional If else statement they are used a lot in React .

But it was a fail, I know what do you mean about the code above.

here the correctly code:

toggleVisibility() {
    this.setState(state => ({
      visibility: state.visibility ? false : true
    }))
  }
1 Like