I\'m having trouble to update the checkbox state after it\'s assigned with default value checked="checked"
in React.
var rCheck = React
this can be done with pure js
<Form.Group controlId="categoryStatus">
<Form.Check
type="checkbox"
label="Category Status Active/In-active"
onChange={this.handleChecked}
/>
</Form.Group>
//Load category to form : to edit
GetCategoryById(id) {
this.UpdateId = id
axios.get('http://localhost:4000/Category/edit/' + id)
.then(response => {
this.setState({
category_name: response.data.category_name,
category_description: response.data.category_description,
is_active: response.data.is_active,
});
response.data.is_active == 1 ? document.getElementById("categoryStatus").checked = true : document.getElementById("categoryStatus").checked = false;
})
.catch(function (error) {
console.log(error);
})
}
in addition to the correct answer you can just do :P
<input name="remember" type="checkbox" defaultChecked/>
In my case I felt that "defaultChecked" was not working properly with states/conditions. So I used "checked" with "onChange" for toggling the state.
Eg.
checked={this.state.enabled} onChange={this.setState({enabled : !this.state.enabled})}
I tried to accomplish this using Class component: you can view the message for the same
.....
class Checkbox extends React.Component{
constructor(props){
super(props)
this.state={
checked:true
}
this.handleCheck=this.handleCheck.bind(this)
}
handleCheck(){
this.setState({
checked:!this.state.checked
})
}
render(){
var msg=" "
if(this.state.checked){
msg="checked!"
}else{
msg="not checked!"
}
return(
<div>
<input type="checkbox"
onChange={this.handleCheck}
defaultChecked={this.state.checked}
/>
<p>this box is {msg}</p>
</div>
)
}
}
I set the state as any[] type. and in the constructor set the state to null.
onServiceChange = (e) => {
const {value} = e.target;
const index = this.state.services.indexOf(value);
const services = this.state.services.filter(item => item !== value);
this.setState(prevState => ({
services: index === -1 ? prevState.services.push(value) && prevState.services : this.state.services.filter(item => item !== value)
}))
}
In the input element
this.onServiceChange(e)}/> this.onServiceChange(e)}/> this.onServiceChange(e)}/> this.onServiceChange(e)}/>
I figured it out after some time. Thought it might help y'all :)
To interact with the box you need to update the state for the checkbox once you change it. And to have a default setting you can use defaultChecked
.
An example:
<input type="checkbox" defaultChecked={this.state.chkbox} onChange={this.handleChangeChk} />