React starts to frustrate me, Using state to toggle elements!

Why this code is not Accepted although it works,
Also I’ve finished 75% of React course, and so far all what I am able to do is show text on html with a lot of cumbersome code, frameworks should make you do much with less code, Am I missing something here?!

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };
    this.toggleVisibility=this.toggleVisibility.bind(this);

  }
toggleVisibility(){
  if (this.state.visibility===false){
    this.setState({visibility:true});
      
    
} else {visibility:false}}
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 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

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

I believe your issue lies here:

toggleVisibility(){
  if (this.state.visibility===false){
    this.setState({visibility:true});
      
    
} else {visibility:false}}

Look at how you formatted your logic after the if(visibility === false) and compare it to your logic after your else.

1 Like

True, libraries and frameworks provide an easier way to write your code. However, consider that they also provide other benefits. For example, React provides a more declarative way to write javascript while still being agnostic enough to form a standard format or convention. In other words, you’re not recreating the wheel while not dealing with opinionated code.

For what’s causing the issue, I would hone in on your block of code in your else statement. I’ll give you a hint:

…else {
this.setState({}) //what object do you need to pass to set your state property visibility to false?
}

1 Like

Thank you very much for your replay, but can you elaborate on:

Regards

toggleVisibility(){
  if (this.state.visibility===false){
    this.setState({visibility:true});
      
    
} else {visibility:false}}
} else {visibility:false}}

didnt have an object. The program will be confused when it comes the true, which one will be false

For anyone still struggling with this, if you want to pass all tests then you need the following code for the toggleVisibility() method (they want you to pass in a function per the directions and to not use ‘this’ in the setState() method) :

image

1 Like