With my e-commerce requirements, I have a filter that consists of multiple checkboxes. The user selects one or multiple checkboxes to filter the list of items in a table.
The checkboxes arrangement looks something like this (sample):
Mathematics
maths checkbox1
maths checkbox2
maths checkbox3
Physics
phy checkbox1
phy checkbox2
phy checkbox3
As any of the filters(checkboxes) are selected, the filters have to be displayed in a component, like this:
With some workaround, I was able to implement a single array containing the selected filter but not sure how to handle this particular way of grouping filters belonging to a same category.
Tried so far:
initialstate = {
filters: [
{
title: '',
options: [
{
name: '',
key: '',
label: '',
}
],
}
],
selected: []
}
const setFilters = (value) => {
setFilterOptions((state) => {
const selectedFilters = state.selected.find(
(obj) => obj === value
);
const selected = selectedFilters
? state.selected.filter(
(obj) => obj !== value
)
: [...state.selected, value];
return {
selected,
filters: [
...state.filters.map((filter) => {
return {
...filter,
options: filter.options.map((ele) => {
return {
...ele,
checked: selected.includes(ele.label)
};
})
};
})
]
};
});
};
The algo that I could think of:
- function
setFilters(value)
takes thelabel
of the filter selected. - component state:
const [filterOptions, setFilterOptions] = useState(initialState);
- inside this function, loop over the
state.selected
array of objects and check to which category thevalue
belongs. - if the
value
does not exist for that category, add it an array. If it already exists (for the same category), then push it to the respective array. - map over the final array to render the names of the filters (as in picture).
I am a bit confused about how to implement this logic actually.
Need a bit help to implement this in the best possible way.
Thank you in advance.
Aucun commentaire:
Enregistrer un commentaire