Use State to Toggle an Element - button click doesn't work

Use State to Toggle an Element - button click doesn't work
0

#1

Tell us what’s happening:
Clicking the rendered button doesn’t do anything when I test inside FCC. Is it supposed to work but just doesn’t in the FCC environment? (has anyone tried it and seen the h1 element pop up?)

Your code so far
Blurring this so as not to spoil the answer.


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.state.visibility = (!this.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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36.

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


#2

Works fine here.
Google Chrome Version 67.0.3396.99 (Official Build) (64-bit)


#3

thanks, my chrome is
Version 68.0.3440.75 (Official Build) (64-bit)

maybe the newer chrome is not working well


#4

You should not directly update this.state as you are trying to do below. You should always use the this.setState method and change the property you want to update.

this.state.visibility = (!this.state.visibility);

The only place where you directly assign state is within the constructor.


#5

Ah! I forgot about that! Thanks it works now.