Home > database >  How to set default state in checkbox when it is not checked- React
How to set default state in checkbox when it is not checked- React

Time:04-22

I am trying to set the default value of the check box when the check box is unchecked

Initial state

 interface stateObject{
  checkbox: boolean | null
 }

 class Component{
 constructor(props){
 super(props)
  this.state = {
  checkbox: null,
}

<Checkbox
 id="checkbox"
 label="controlled"
 value={this.state.checkbox}
 onChange={this.ChangeValue}
 />

 ChangeValue= (event) => {
this.setState(
  (prevState) => ({
    checkbox: !prevState.checkbox,
  })
})

When I click on the checkbox it sets to true which is fine when I unselect/uncheck the checkbox I need to set it to the default state value(null) instead of false

CodePudding user response:

If you want the value to alternate between true and null that can be done like this:

this.setState(prevState => ({
  checkbox: prevState.checkbox ? null : true
});
  • Related