React - Use State to Toggle an Element

Tell us what’s happening:

Why we need to check true or false in constructor?
I have seen hint and see that in constructor the hint author was doing
this.toggleVisibility = this.toggleVisibility.bind(this);
but in the method, they are setting the state but what I do not understand why the above line in constructor?

My code is messy because I do not understand much

Your code so far

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

Challenge Information:

React - Use State to Toggle an Element

You need to bind the method, and the method name is toggleVisibility not visibility.

this.visibility = !this.visibility.bind(this);

There is no such binding in the hints, or anywhere I can tell.


Maybe my mistake, sorry but I cannot understand why we have this.toggleVisibility = this.toggleVisibility.bind(this); is in constructor.

Read the docs I posted or review this challenge again.