Using setState with React Checkbox onChange In React, the best way to do this is via the useState hook. This is different from normal JavaScript because we are unable to access the value of the checkbox directly from its DOM component: /* Create a checkbox functional component.
Use the target. checked property on the event object to check if a checkbox is checked in React, e.g. if (event. target. checked) {} .
To uncheck a checkbox programmatically in React, we can set the checked prop of the checkbox to a state. We have the checked state that we used to set the checked prop of the checkbox. Then we add a button that calls setChecked to toggle the checked value when we click the button.
To get the checked state of your checkbox the path would be:
this.refs.complete.state.checked
The alternative is to get it from the event passed into the handleChange
method:
event.target.checked
It's better not to use refs in such cases. Use:
<input
type="checkbox"
checked={this.state.active}
onClick={this.handleClick}
/>
There are some options:
checked
vs defaultChecked
The former would respond to both state changes and clicks. The latter would ignore state changes.
onClick
vs onChange
The former would always trigger on clicks.
The latter would not trigger on clicks if checked
attribute is present on input
element.
If you have a handleChange
function that looks like this:
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
}
You can create a custom onChange
function so that it acts like an text input would:
<input
type="checkbox"
name="check"
checked={this.state.check}
onChange={(e) => {
this.handleChange({
target: {
name: e.target.name,
value: e.target.checked,
},
});
}}
/>
In the scenario you would NOT like to use the onChange handler on the input DOM, you can use the onClick
property as an alternative. The defaultChecked
, the condition may leave a fixed state for v16 IINM.
class CrossOutCheckbox extends Component {
constructor(init){
super(init);
this.handleChange = this.handleChange.bind(this);
}
handleChange({target}){
if (target.checked){
target.removeAttribute('checked');
target.parentNode.style.textDecoration = "";
} else {
target.setAttribute('checked', true);
target.parentNode.style.textDecoration = "line-through";
}
}
render(){
return (
<span>
<label style={{textDecoration: this.props.complete?"line-through":""}}>
<input type="checkbox"
onClick={this.handleChange}
defaultChecked={this.props.complete}
/>
</label>
{this.props.text}
</span>
)
}
}
I hope this helps someone in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With