Use-state-to-toggle-an-element

Use-state-to-toggle-an-element
0.0 0

#1

Tell us what’s happening:
This is a beta exercise. I am not so sure why it’s not working. Can someone help please?

Thanks,
Phillip

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){
      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/65.0.3325.181 Safari/537.36.

Link to the challenge:


#2

You are setting the state object by passing an object and waiting for React to perform a shallow merge: therefore being an object this is not a valid syntax:

      this.setState({
        visibility = false;
      })

However if you change it to a proper object, with : and , it works :slight_smile:

this.setState({
  changed: true,
  isAwesome: false,
  a: 'string',
  b: [1,2,3],
}) 

Hope it helps :+1:


#3

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

// change code above this line


#4

Use ther “!” operator to update the boolean value inside the component state. The toggleVisibility() method would be like this:

toggleVisibility() {
    this.setState({
        visibility: !this.state.visibility
    });
}

#5

Remember that setState takes an object as an argument. You are forgetting object syntax. To assign a value to an object property, you do not use =

Edit: Just realized this is an old thread which probably has already been solved.