Currently, I have many checkboxes which all obviously correlate to boolean values that need to be passed on onSubmit. I had something like this initially:
const [value, setValue] = React.useState({
alpha: true,
beta: false,
charlie: false,
// twenty or so more
});
...
<CheckboxComp
aria-label="id"
checked={value.alpha}
onChange={() => setValue({ alpha: !value.alpha})}
label="id"
/>
Which was throwing me:
Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
Then I came across this.
- Through Input
const [state, setState] = useState({ fName: "", lName: "" });
const handleChange = e => {
const { name, value } = e.target;
setState(prevState => ({
...prevState,
[name]: value
}));
};
<input
value={state.fName}
type="text"
onChange={handleChange}
name="fName"
/>
<input
value={state.lName}
type="text"
onChange={handleChange}
name="lName"
/>
***************************
- Through onSubmit or button click
setState(prevState => ({
...prevState,
fName: 'your updated value here'
}));
Which is nearly as close as I got but I was having trouble toggling true/false with something that was meant for strings on input. Any help, I know it's a silly question but it's a lot better than continuing onwards with useState(false) x20, the furthest thing from optimized.
Now I have something like this!
const [value, setValue] = React.useState({
alpha: true,
beta: false,
charlie: false,
});
const handleChange = e => {
const { name, value } = e.target;
setValue(prevState => ({
...prevState,
[name]: value
}));
};
console.log(value)
...
<CheckboxComp
aria-label="id"
checked={value.alpha}
onChange={handleChange}
name="alpha"
label="id"
/>
but console.log shows
alpha: "true"