State ToggleVisibility

State ToggleVisibility
0

#1

Tell us what’s happening:

I have the code set to turning from false to true. Not sure how to code it to turn true back to false.

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({
    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/69.0.3497.100 Safari/537.36.

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


#2

Try using an IF statement to make it true if its false and false if its true


#3

Think about what happens if you add ! in front of a Boolean variable.


#4

Thanks for the response. I have tried a few ways to use a conditional. I am not familiar how code “if” in react using setState and a property and value;
I have also tried using myComponet.state.visibility this.state.visibility, and this.visibility. Please point me in the right direction. Thanks.


#5

In react, you can add regular JS code above the return method (and in the return method via JSX). So you can create a simple if statement around the visibility and if it is true can change visibility to false via this.setstate, or vice versa


#6

React is is JavaScript. The hint I gave you earlier about the ! character in front a Boolean variable applies here.

Let’s say I have a variable named found and initialize it to the value false.

var found = false;

If I want to make found equal to true, I could write:

found = true;

OR I could use the ! in front of found like:

found = !found; // now found is true;

Now if I want to make found equal to false again, I just write:

found = !found; // now found is false

See if you can apply this when setting the MyComponent’s this.state visibility property.