Clicking the button element should toggle the visibility property in state between true and false

Tell us what’s happening:
Clicking the button element should toggle the visibility property in state between true and false .

getting this issue state in above line
function toggleVisibility() isn’t returning true or false value after setting state in that!

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 =>{
  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 (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:

Your setState function doesn’t return an object at the moment, because JavaScript interprets the opening curly brace (after the arrow) as the beginning of the function body. To prevent this, all you have to do is add a set of brackets to wrap your object:

toggleVisibility () {
this.setState(state =>({
  visibility : !state.visibility
}))
}
1 Like

oh!
That was bad of me!
Thank you so much for correcting me.

Honestly this one is a horrible gotcha of JS!

1 Like

yeah! you are into making arrow Functions and boom you missed setState thing!