I am working on an application that has a form and radio buttons.
For one of the radio buttons, it has an option that can be toggled on/off with a checkbox.
I want the checkbox to be disabled if the respective radio button is NOT selected, its default behavior to work when is it active, and for it to be disabled AND unchecked if a different radio button is then selected.
I have gotten all of those behaviors to work, but React is throwing an exception that says,
app-index.js:31 Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
My "working" solution:
const [checkboxActive, setCheckboxActive] = useState<boolean | undefined>(false);
const handleOptionClick = (option?: string) => {
setSelected(true);
if (option) {
setEveryOtherLetterSelected(true);
setCheckboxActive(undefined);
} else {
setEveryOtherLetterSelected(false);
setCheckboxActive(false);
}
}
<input type="checkbox" name="first" disabled={everyOtherLetterSelected ? false : true} checked={checkboxActive} />
From this thread (Setting a checkbox "check" property in React), I see that this is a weird thing with React and checkbox type inputs where its "checked" value is either a boolean or undefined. I have tried putting the "!!" in front of the condition (!!checkboxActive
), but that changes the behavior.
Is there a more acceptable way to do this where React won't yell at me?
Aucun commentaire:
Enregistrer un commentaire