Reputation: 3014
I have a component where I can select several checkboxes. For each selected checkbox, a chip is generated that illustrates the selected checkboxes. These chips have a remove handler that can remove the selections (like the checkbox itself9. This works so far, but if I use the chips to remove the selection, the state of the corresponding checkbox is not adjusted.
What am I doing wrong?
Here is the rendering of my checkboxes (simplified):
{filteredData(data)?.map((data, index) => (
<CheckBox
// some other props
selected={selected.includes(data.id)}
onChange={() => handleState(data.id)}
/>
))}
Here is the rendering of my chips:
{selected.map((checkbox) => (
<Chip
onDelete={() => handleState(checkbox.id, true)}
/>
))}
Here is the handler method:
const [selected, setSelected] = useState([]);
const handleState = (id: string, withC?: boolean): void => {
const selectedCB = [...selected];
const index = selectedCB.findIndex((item) => item.id === id);
if (index > -1 || withC) {
selectedCB.splice(index, 1);
} else {
selectedCB.push(data.find((item) => item.id === id));
}
setSelected(selectedCB);
};
Upvotes: 0
Views: 259
Reputation: 1018
You have the issue with the checkbox selected
condition. The following line:
selected={selected.includes(data.id)}
Notice that selected
is an array of object, so checking includes()
with data.id
will not work. Replace your selected logic with
selected={selected.find(cb => cb.id === data.id)
It should work!
Upvotes: 1