'How do i set sate based on the condition in checkbox Change function reactjs

In the checkbox the default value is null and I am setting it as true when required but also I thought of one more condition that needs to be set when the checkbox is already selected I want to unselect it and set the value as false instead of null.

Assume alwaysSelected -if this is selected it is true(onload) based on this condition i should update the state

this.state = {
checkbox: null,
}
this.props.alwaysSelected=true

<Checkbox
onChange={this.ChangeValue}
/>

ChangeValue= (event) => {
this.setState(checboxState=> ({
checkbox: checboxState.checkbox ? null : true
});
})

Just say prevState.checkbox -true on a load of the page then it just gives null but need to set it as false

Option tried is setState callback and componentDidUpdate but failed to acheive.

can we do this in another approach??



Solution 1:[1]

You can pass the checkbox state to the Checkbox component as value and change the event:

ChangeValue = () => this.setState({checkbox:!checkbox});

or if event returns true/false

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hesam