I have two React components, namely, Form
and SimpleCheckbox
.
SimpleCheckbox
uses some of the Material UI components but I believe they are irrelevant to my question.
In the Form
, useEffect calls api.getCategoryNames()
which resolves to an array of categories, e.g, ['Information', 'Investigation', 'Transaction', 'Pain']
.
My goal is to access checkboxes' states(checked or not) in the parent component(Form
). I have taken the approach suggested in this question.(See the verified answer)
Interestingly, when I log the checks
it gives(after api call resolves):
{Pain: false}
What I expect is:
{
Information: false,
Investigation: false,
Transaction: false,
Pain: false,
}
Further More, checks
state updates correctly when I click into checkboxes. For example, let's say I have checked Information
and Investigation
boxes, check
becomes the following:
{
Pain: false,
Information: true,
Investigation: true,
}
Here is the components:
const Form = () => {
const [checks, setChecks] = useState({});
const [categories, setCategories] = useState([]);
const handleCheckChange = (isChecked, category) => {
setChecks({ ...checks, [category]: isChecked });
}
useEffect(() => {
api
.getCategoryNames()
.then((_categories) => {
setCategories(_categories);
})
.catch((error) => {
console.log(error);
});
}, []);
return (
{categories.map(category => {
<SimpleCheckbox
label={category}
onCheck={handleCheckChange}
key={category}
id={category}
/>
}
)
}
const SimpleCheckbox = ({ onCheck, label, id }) => {
const [check, setCheck] = useState(false);
const handleChange = (event) => {
setCheck(event.target.checked);
};
useEffect(() => {
onCheck(check, id);
}, [check]);
return (
<FormControl>
<FormControlLabel
control={
<Checkbox checked={check} onChange={handleChange} color="primary" />
}
label={label}
/>
</FormControl>
);
}