React - Use State to Toggle an Element

This drill gives me a class component, and requires me to define a toggleVisibility function that toggles the visibility state between true and false.
The only reason this code doesn’t work is because setState doesn’t have an anonymous function passed to it.

  1. Why does the drill require that setState gets an anonymous function passed to it in order to toggle the visibility state? Is it considered the best practice in this scenario?
  2. Why does the binding need to be in the constructor?
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.state.visibility) {
      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>
      );
    }
  }
}

Link to the challenge:

hello and welcome back to fcc forum :slight_smile:

  • its Class structure “ways of doing things”, you can read up more about how and what “constructor” does within a “Class” structure for more clarity on this matter

happy coding :slight_smile:

1 Like