Possible bug in - React: Use State to Toggle an ElementPassed chapter

Tell us what’s happening:

The solution which I entered does not passes. Is there any issue with this function? I assume this is a bug in freecodecamp.

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

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 => {
    visibility: !state.visibility
  });
}



// 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 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36.

Challenge: Use State to Toggle an Element

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

There is a bug in your anonymous function passed into setState(). Arrow functions can return objects but you must do something special in order to return an object.

I don’t get it. Can you please explain what you mean by something special ?

You are missing a set of parentheses.

Arrow functions can be written as follows:

() => {
  return some_value
}

The curly braces encompass the body of the function. You can convert this to one line:

() => some_value

In which you lose the curly braces. So when you have curly braces after the arrow then that means you will have a function body with a return statement. You don’t have a return statement in yours because you are trying to return an object using the one liner format. But since an object uses curly braces the JS parser thinks you are defining a function body instead of returning an object. If you want to return an object in a one line arrow function then you need to add something around the object so the JS parser doesn’t think you are defining a function body. Sky020 gave you a hint.

1 Like