I am trying to implement multiple checkboxes but onChange takes effect only after another click on other checkboxes here is the code snippet :
here I Initialize the array of objects that's going to get rendered as checkboxes on component render
const contentFilters = ['Videos', 'Life Events', 'Collabs'];
const [selectedContentFilters, setSelectedContentFilter] = useState([]);
useEffect(() => {
setSelectedContentFilter(
contentFilters.map((filter, index) => {
return {
id: index + 1,
label: filter,
checked: false,
};
}),
);
}, []);
here is how I map the array of objects into checkboxes components
{selectedContentFilters.map((filter) => {
return (
<DropDownItem key={filter.id}>
<CheckboxContainer>
<input
id={filter.id}
type={'checkbox'}
onChange={() => {
_setSelectedContentFilter(filter.id);
}}
checked={filter.checked}
name={filter.label}
/>
<Label>{filter.label}</Label>
</CheckboxContainer>
</DropDownItem>
);
})}
here is the _selectedContentFilter that gets called once the onChange triggers to update the array state, I Clone the array in order to dont have the same reference and cause the re-render on state update :
const _setSelectedContentFilter = (id) => {
let cloneSelectedContentFilter = [...selectedContentFilters];
cloneSelectedContentFilter = cloneSelectedContentFilter.map((filter) => {
if (filter.id === id) {
filter.checked = !filter.checked;
}
return filter;
});
setSelectedContentFilter(cloneSelectedContentFilter);
};
The issue was caused from the react-bootstrap dropdown item component that cause the checkboxes to delay the re-render .