Use State to Toggle an Element React

Use State to Toggle an Element React
0.0 0

#1

Tell us what’s happening:

Hi guys, I’m having difficulties debugging this. Can someone help me with it.

Thank you!

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=true){
    this.setState = ({
      visibility: false
    });
}
else{
   this.setState = ({
      visibility: true
})

  // 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/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


#2

The debug difficult is due to the missing curly braces after your else statement ( two are missing).
I would add a couple of things:

  • if (this.state.visibility=true)

    in js = is assignment, == is loose equality, === is stricly equality

  • this.setState = ({ […] })

    This.setState is a method, that equal sign shouldn’t be there ^^


#3

I learnt something new today. Thank you!!