React - Use State to Toggle an Element

Tell us what’s happening:
Describe your issue in detail here.

The test passes, but nothing observable happens when I click the button.
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 => {
        if (state.visibility === false) {
          state.visibility = true;
        } else state.visibility = false;
      });
    }
  // 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 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/117.0

Challenge: React - Use State to Toggle an Element

Link to the challenge:

Hi there and welcome to our community!

Your code shouldn’t pass as you can’t set state like this. Clicking the button in your code isn’t changing the state (i.e. visibility remains false).

If you were to explicitly set the state to true you could write:

this.setState({
  visibility: true
});

However, inside this.setState you have a function which should return a value, subject to a condition. In this case, you should return the correct state object to meet the condition (i.e. {visibility: true} or {visibility: false}).

Alternatively, there is a nifty way of toggling state without needing to use a conditional statement at all. You can use setState to directly set the value of visibility to the opposite of its current value.

Technically you can, which is why the tests pass (it checks the state).

But React won’t know to re-render when mutating state which is why the code doesn’t actually do what it is supposed to do. If you call this.forceUpdate() after the setState you can see it works, but that obviously isn’t how you are meant to use React.


But yes, the test should check for the existence of the DOM nodes and not just the state update.

Edit: I made a PR for it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.