The problem: I have a selection of 3 radio buttons, and I need to allow users to unselect a radio button they have previously selected by clicking on it (toggle state based on user selection of radio button). Adding a "none" or "clear selections" button is not an option. So this needs to be either radio buttons that allow un-selecting, or checkboxes that allow only 1 selection.
How on earth do I do this in react cleanly? Semi-cleanly?
Disclaimers:
Mhm, this solution is not great, but, you can do the following:
onChange -> you just switch the stateonClick -> verify if the value is the one that you're already having in the state. If so, set the state to null.Look at this CodeSandbox
Or, you can use a checkbox, and always keep 1 item in state at a time. And once that is clicked again, just clear the state.
import React from 'react'
const ExclusiveCheckBoxes = (props) => {
const allUnchecked = {option1:false, option2:false, option3:false};
const [options, setOptions] = React.useState(allUnchecked);
const chkChanged = e => {
setOptions({...allUnchecked, [e.target.name]: e.target.checked});
}
return (
<div>
<h1>ExclusiveCheckBoxes</h1>
<input type="checkbox" name="option1"
checked={options.option1} onChange={chkChanged}/>
<input type="checkbox" name="option2"
checked={options.option2} onChange={chkChanged}/>
<input type="checkbox" name="option3"
checked={options.option3} onChange={chkChanged}/>
</div>
)
}
export default ExclusiveCheckBoxes