Answers for "react setstate toggle"

1

toggle with setState

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 === true) {
         return { visibility: false };
       } else {
         return { 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>
      );
    }
  }
};
Posted by: Guest on April-22-2021
2

react toggle state

this.setState(prevState => ({
  iover: prevState.iover === 'hide' ? 'show' : 'hide'
}));
Posted by: Guest on April-10-2021
0

toggle boolean state react

this.setState(prevState => ({
  check: !prevState.check
}));
Posted by: Guest on June-25-2020
0

react toggle state

this.setState(prevState => ({
  iover: !prevState.iover
}));
Posted by: Guest on July-25-2020

Browse Popular Code Answers by Language