React-this.setState-method(React)

Tell us what’s happening:
can someone explain to me what this means below:-
.
Currently, there is no way of updating the visibility property in the component’s state . The value should toggle back and forth between true and false. There is a click handler on the button which triggers a class method called toggleVisibility() . Pass a function to setState to define this method so that the state of visibility toggles to the opposite value when the method is called. If visibility is false , the method sets it to true , and vice versa.

  **Your code so far**

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

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

Challenge: Use State to Toggle an Element

Link to the challenge:

Right now, you’re using setSyate and trying to create a toggleVisibility thing on the state object.

You’re being asked to create a toggleVisibility function that uses the setState within it.

1 Like

Hi @Dico-Akidiva ,

The challenge is that you have to toggle on the button to see the text.

Initially, the visibility state is false, you have to set it to true by using the setState method.
You have to call the setState method inside toggleVisibility() function.

Since this is a class component, do not forget to bind the toggleVisibility() function.

Below is the how you bind a function:
this.toggleVisibility = this.toggleVisibility.bind(this);

I hope it helps

2 Likes

thank you @nivethakrishnan72 let me try it and see if I can get somewhere.

1 Like

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