'Show total number of selected filters array of items in React
I have the following problem. In widgetFilters array (length===3) i want to show the numbers of selected items in the header of the Filter.
const [selectedFilters, setSelectedFilters] = useState([]);
In code snipet below i map through all the widgetFilter array and making 3 Accordion with the headline the name typeName of filter and then the options that filter contains e.g.
<Stack>
{widgetFilters.map((filter) => (
<FilterWidgetAccordion
key={filter.id}
headline={filter.typeName}
list={filter.options}
selectedFilters={selectedFilters}
setSelectedFilters={setSelectedFilters}
/>
))}
</Stack>
FilterWidgetAccordion.js
<Fragment>
<Accordion>
<AccordionSummary aria-controls="panel1a-content" id="panel1a-header">
<StyledTypography>{headline}</StyledTypography>
</AccordionSummary>
<AccordionDetails>
{list?.map((filterItem) => {
return(
<Button
onClick={() => {
const list = [...selectedFilters];
const index = list.indexOf(filterItem);
index === -1 ? list.push(filterItem) : list.splice(index, 1);
setSelectedFilters(list);
}}
key={filterItem.value}
>
{filterItem.value}
</Button>
)})}
</AccordionDetails>
</Accordion>
</Fragment>
I want next to e.g "Product Category" title to add the number of selected buttons look the image below.
Solution 1:[1]
You have to separate filters for each widget then display filters length in the headline, here is an example :
const updateWidgetFilters=(myFilters, widgetTypeId)=>{
setSelectedFilters((prevSelectedFilters)=>{
const selectedElement = prevSelectedFilters?.find(({typeId})=>typeId===widgetTypeId);
if(selectedElement) {
selectedElement.filters= myFilters;
return [...prevSelectedFilters]
}
return [...prevSelectedFilters, {typeId: widgetTypeId, filters: myFilters}];
});
}
...
<Stack>
{widgetFilters.map((filter) => (
<FilterWidgetAccordion
key={filter.id}
headline={
filter.typeName+' '
+(selectedFilters?.find(({typeId})=>typeId===filter.typeId)?.filters?.length || 0)
}
list={filter.options}
selectedFilters={selectedFilters?.find(({widgetId})=>typeId===filter.typeId)?.filters || []}
setSelectedFilters={(filters)=>updateWidgetFilters(filters, filter.typeId)}
/>
))}
</Stack>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |