React - Use State to Toggle an Element

Tell us what’s happening:

Hi! Functionally, my code works - when I click the button, the state seems to toggle and the text appears/disappears from the screen.

But I keep getting an error on the console: “An anonymous function should be passed to setState”. I’ve reviewed my code a couple of times and did some improvements, but I still don’t understand fundamentally what the console call is trying to tell me. I understand the solutions posted on the Guide, but I’d love to know what’s the issue with mine instead. Thanks!

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; rv:129.0) Gecko/20100101 Firefox/129.0

Challenge Information:

React - Use State to Toggle an Element

Hi @palhares.f

Pass a function to setState to define this method so that the state of visibility toggles to the opposite value when the method is called.

The tests are searching for a specific sequence of code.

Your code is wrapping the method in a conditional.

Happy coding

1 Like

It is specifically asking that you use an updater function with setState.

this.setState(state => ({
  counter: state.counter + 1
}));

Example
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dark: false
    };

    this.toggleDarkMode = this.toggleDarkMode.bind(this);
  }

  toggleDarkMode() {
    this.setState((state) => ({ dark: !state.dark }))
  }

  // Change code above this line
  render() {
    if (this.state.dark) {
      return (
        <div>
          <button onClick={this.toggleDarkMode}>Toggle Theme</button>
          <h1>Light mode</h1>
        </div>
      );
    } else {
      return (
        <div>
          <button onClick={this.toggleDarkMode}>Toggle Theme</button>
          <h1>Dark mode</h1>
        </div>
      );
    }
  }
}
1 Like