React - Use State to Toggle an Element

**Why we used this.toggleVisibility: this.toggleVisibility.bind(this); **

Your code so far

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };
    // Change code below this line

    // Change code above this line
    this.toggleVisibility=this.toggleVisibility.bind(this)
  }
  // Change code below this line
  toggleVisibility(){
    this.setState(state=>
    {
      if(state.visibility==false)
      {
        return{
          visibility:true
        }
      }
      else
      {
        return{
          visibility:false
        }
      }
    })
  }

  // 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/115.0.0.0 Safari/537.36

Challenge: React - Use State to Toggle an Element

Link to the challenge:

hello and welcome to fcc forum :slight_smile:

  • are you familiar with “class” structure in javascript?

perhaps these might help you understand that

happy reading :slight_smile:

It was explained in the previous challenge.

The legacy React docs explain it as well. The new React docs shows you it in the way a modern React app that still uses Class components would do it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.