React - Use State to Toggle an Element

Tell us what’s happening:
Describe your issue in detail here.
@camperextraordinaire
please check this it gets submitted successfully

   **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)=>{
    if (state.visibility===false){
      return state.visibility=true}
      else {
        return state.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/103.0.0.0 Safari/537.36

Challenge: React - Use State to Toggle an Element

Link to the challenge:

Theres a syntax error here and

Here, remember you need to return a boolean but how do you use javascript within react when its not JSX?

Any other contributors can confirm this guide?

Your code is passing for me.

But it isn’t correct, you are mutating the state inside the updater function. If you run this in strict mode it will not work. It would double-invoke the updater function.

Detecting unexpected side effects

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

You can turn off strict mode (inside index.js) in this example to see it in action

1 Like

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