Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading