Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle boolean state of react component?

I'd like to know how to toggle a boolean state of a React component. For instance:

I have a boolean state check in the constructor of my component:

constructor(props, context) {     super(props, context);     this.state = {       check: false    }; }; 

I am trying to toggle the state each time my checkbox is clicked, using the this.setState method:

<label>   <input     type=checkbox"     value="check"     onChange={(e) => this.setState({check: !check.value})}   />   Checkbox </label> 

Of course I get a Uncaught ReferenceError: check is not defined. So how can I achieve this?

like image 434
noob Avatar asked Nov 01 '16 12:11

noob


People also ask

How do you toggle boolean?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

How do you toggle State in React hooks?

toggle is our state variable. This is what we'll reference when we want to get the current state of toggle . setToggle is the function that we'll use to actually update the state of our component. useState(false) this is how we 'hook' into the React feature itself.

How do you toggle in a functional component React?

To toggle a boolean state in a React component, we can pass in a function that takes the existing value of the state and returns the next state into a state setter function. We call the useState hook to create the check state.


2 Answers

Since nobody posted this, I am posting the correct answer. If your new state update depends on the previous state, always use the functional form of setState which accepts as argument a function that returns a new state.

In your case:

this.setState(prevState => ({   check: !prevState.check })); 

See docs


Since this answer is becoming popular, adding the approach that should be used for React Hooks (v16.8+):

If you are using the useState hook, then use the following code (in case your new state depends on the previous state):

const [check, setCheck] = useState(false); // ... setCheck(prevCheck => !prevCheck); 
like image 139
Dane Avatar answered Sep 17 '22 18:09

Dane


You should use this.state.check instead of check.value here:

this.setState({check: !this.state.check}) 

But anyway it is bad practice to do it this way. Much better to move it to separate method and don't write callbacks directly in markup.

Upd: As pointed out in comments this approach might lead to unexpected results since React's state is asynchronous. The correct way in this case will be to use callback:

this.setState(({ check }) => ({ check: !check })); 
like image 24
Eugene Tsakh Avatar answered Sep 18 '22 18:09

Eugene Tsakh