Use State to Toggle an Element

Tell us what’s happening:
Something seems to be wrong with the toggle function but I’m struggling to debug this.

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() {
    if (this.state.visibility = false) {
      this.setState = {
        visibility: true
      }
    }
    if (this.state.visibility = true) {
      this.setState = {
      visibility: false
      }
    }
  }
  // change code above this line
  render() {
  else  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/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/use-state-to-toggle-an-element

this.setState is a function, not an object assignment. So it should be this.setState({}).

Also, you can use the shorthand to flip a variable. So if you have

this.state = {
  visibility: true
}

// to flip it, just do
toggleVisibility() {
// this.setState can also get a callback to access previous state
 return this.setState(prevState => ({visibility: !prevState.visibility}))
}

The ! sets the value to to opposite of what it is.

if (this.state.visibility = true)
There it’s must be == instead of =.
And better just
if (this.state.visibility) ,cause it’s equal to if (this.state.visibility == true)
and also as JM-Mendez wrote = this.setState must be a function.

Change your toggleVisibility() to this, simple and easy to understand

toggleVisibility() {
    if(this.state.visibility) {
      this.setState({
        visibility: false,
      })
    } else {
      this.setState({
        visibility: true,
      })
    }
    
  }
1 Like