How To Toggle Boolean State Of A React Component?
Solution 1:
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);
Solution 2:
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 }));
Solution 3:
Here's an example using hooks (requires React >= 16.8.0)
// import React, { useState } from 'react';const { useState } = React;
functionApp() {
const [checked, setChecked] = useState(false);
consttoggleChecked = () => setChecked(value => !value);
return (
<inputtype="checkbox"checked={checked}onChange={toggleChecked}
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<scriptcrossoriginsrc="https://unpkg.com/react@16/umd/react.development.js"></script><scriptcrossoriginsrc="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><divid="root"><div>
Solution 4:
Use checked
to get the value. During onChange
, checked
will be true
and it will be a type of boolean
.
Hope this helps!
classAextendsReact.Component {
constructor() {
super()
this.handleCheckBox = this.handleCheckBox.bind(this)
this.state = {
checked: false
}
}
handleCheckBox(e) {
this.setState({
checked: e.target.checked
})
}
render(){
return<inputtype="checkbox"onChange={this.handleCheckBox}checked={this.state.checked} />
}
}
ReactDOM.render(<A/>, document.getElementById('app'))
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid="app"></div>
Solution 5:
Try:
<label><inputtype=checkbox" value="check"onChange = {(e) => this.setState({check: !this.state.check.value})}/> Checkbox </label>
Using check: !check.value
means it is looking for the check
object, which you haven't declared.
You need to specify that you want the opposite value of this.state.check
.
Post a Comment for "How To Toggle Boolean State Of A React Component?"