React - Use State to Toggle an Element

Tell us what’s happening:
I am trying to get the else - if statement replaced by the ternary operator and I do not know why I can’t get this logic to work

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 => {
      (state.visibility ? {visibility: false} : {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; rv:105.0) Gecko/20100101 Firefox/105.0

Challenge: React - Use State to Toggle an Element

Link to the challenge:

The above link explains the syntax and gives a few good examples for using the ternary operator.
The first thing is to enclose the test condition in parenthesis as shown in the generic example below:

let var = (test condition) ? expression1 : expression2

The ternary operator evaluates the test condition, and

  • If the condition is true, expression1 will be assigned to var.
  • If the condition is false, expression2 will be assigned to var.

So in the corrected code below you are essentially assigning the result of the ternary operator to visibility which is the opposite of the current state of visibility

toggleVisibility() {
   this.setState(state => ({
   visibility:(state.visibility) ? false : true
}));

}

Hope this helps.

It is worth pointing out that with ternary (and often if/else) it would be considered ugly to set a value to true/false. Usually it would be done like:

this.setState(state => ({
   myBooleanValue: !state.myBooleanValue
}))
1 Like

I see now, thank you so much!