How to toggle boolean state of react component?
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);
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.
Here's an example using hooks (requires React >= 16.8.0)
// import React, { useState } from 'react';
const { useState } = React;
function App() {
const [checked, setChecked] = useState(false);
const toggleChecked = () => setChecked(value => !value);
return (
<input
type="checkbox"
checked={checked}
onChange={toggleChecked}
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"><div>