I'm having trouble getting a checkbox to update to match my state.
The checkbox is rendered as so:
<div className={"form-group row " + (this.state.displayFormElements.infoRequiredApiCall ? '' : 'd-none')}>
<div className="col-sm-2">Get Setup API Call</div>
<div className="col-sm-10">
<div className="form-check">
<input className="form-check-input" type="checkbox" id="infoRequiredApiCall" checked={this.state.pendingSubmission.infoRequiredApiCall} onChange={this.handleCheckboxUpdate} />
<label className="form-check-label" htmlFor="gridCheck1">
Required
</label>
</div>
</div>
</div>
The onChange function is:
handleCheckboxUpdate(e) {
e.preventDefault()
let pendingSubmission = { ...this.state.pendingSubmission }
if (this.state.pendingSubmission[e.target.id] === false) {
pendingSubmission[e.target.id] = true
} else {
pendingSubmission[e.target.id] = false
}
this.setState({ pendingSubmission })
}
This is the behaviour I'm seeing.
1. Checkbox unticked + state value false
I click the checkbox
2. Checkbox unticked + state value true
I click the checkbox
3. Checkbox ticked + state value true
I click the checkbox
4. Checkbox ticked + state value false
I click the checkbox
5. Checkbox unticked + state value false
I've tried a few different solutions, including a more conventional onChange function that writes the value to the state (as 'on' when checked as it behaves by default) but figured true/false was more straightforward.
What am I missing here. I think I understand setState's asynchronous behaviour and can update the value of dropdowns and text inputs no problem using this method.
Thanks!
Aucun commentaire:
Enregistrer un commentaire