Set checkbox value in React JS
not sure but try it :
React.createElement('input',{type: 'checkbox', defaultChecked: false});
or
<input type="checkbox" checked={this.state.chkbox} onChange={this.handleChangeChk} />
or
var Checkbox = React.createClass({
getInitialState: function() {
return {
isChecked: true
};
},
toggleChange: function() {
this.setState({
isChecked: !this.state.isChecked // flip boolean value
}, function() {
console.log(this.state);
}.bind(this));
},
render: function() {
return (
<label>
<input
type="checkbox"
checked={this.state.isChecked}
onChange={this.toggleChange} />
Check Me!
</label>
);
}
});
React.render(<Checkbox />, document.getElementById('checkbox'));
This is kind of old but in case it helps.
I started relying on this syntax
Declare in the class, a variable to store the state:
const [agreeToAllTerms, setAgreeToAllTerms] = useState(false);
Declare the checkbox
<Checkbox checked={agreeToAllTerms} onChange={(event)=> {handleChangeChk(event)}}/>
And then in the function checked the current state of the checkbox like this.
const handleChangeChk = (chkValue) => {
setAgreeToAllTerms(chkValue.target.checked);
}
Your example is not working properly because you are checking the value before this.setState()
is completed. Don't forget that this.setState()
does not immediately mutate the state
.
To fix it, you can create a function where you update the value of the checkbox
updateCheckBox(){
if(parseInt(this.state.firstValue) != parseInt(this.state.minValue) || parseInt(this.state.secondValue) != parseInt(this.state.maxValue)){
this.setState({chcboxValue: true});
}else{
this.setState({chcboxValue: false});
}
}
and then pass it to your handleChange
this.setState()
calls.
handleChange(name, event){
let value = event.target.value;
//We set the state value depending on input that is clicked
if(name === "second"){
if(parseInt(this.state.firstValue) < parseInt(value)){
this.setState({secondValue:value}, this.updateCheckBox);
}
}else{
//The first value can't be greater than the second value
if(parseInt(value) < parseInt(this.state.secondValue)) {
this.setState({firstValue: value}, this.updateCheckBox);
}
}
jsfiddle
we can set an onChange
prop on the input
field and handle the event.
App.js
import {useState} from 'react';
export default function App() {
const [isChecked, setIsChecked] = useState(false);
const handleChange = event => {
setIsChecked(event.target.checked);
// ð️ this is the checkbox itself
console.log(event.target);
// ð️ this is the checked value of the field
console.log(event.target.checked);
};
return (
<div>
<input
type="checkbox"
id="checkbox-id"
name="checkbox-name"
onChange={handleChange}
checked={isChecked}
/>
</div>
);
}