Handling Multi-Selection and Hierarchical Facets
Show code on how to enable multi-selection within faceted search options and how to structure hierarchical facets for nested data categorization in React TanStack Table.
const [selectedFacets, setSelectedFacets] = useState({});
function handleFacetToggle(facetCategory, facetValue) {
const currentSelectedFacets = {...selectedFacets};
if (currentSelectedFacets[facetCategory]?.includes(facetValue)) {
currentSelectedFacets[facetCategory] = currentSelectedFacets[facetCategory].filter(item => item !== facetValue);
if (currentSelectedFacets[facetCategory].length === 0) delete currentSelectedFacets[facetCategory];
} else {
currentSelectedFacets[facetCategory] = currentSelectedFacets[facetCategory] ? [...currentSelectedFacets[facetCategory], facetValue] : [facetValue];
}
setSelectedFacets(currentSelectedFacets);
}
This code snippet is for handling multiple selection within faceted search options. It maintains a state of selected facets, and toggles selection status of a given facet value within a category when invoked.
const hierarchicalFacets = {
category: {
Electronics: ['Phones', 'Laptops'],
Clothing: ['Men', 'Women']
}
};
function renderHierarchicalFacets(facetCategory, facets) {
return facets[facetCategory].map(subCategory => (
<div key={subCategory}>
<h4>{subCategory}</h4>
{hierarchicalFacets[facetCategory][subCategory].map(item => (
<Checkbox
key={item}
label={item}
onChange={() => handleFacetToggle(facetCategory, item)}
checked={selectedFacets[facetCategory]?.includes(item) || false}
/>
))}
</div>
));
}
This piece demonstrates handling hierarchical facets for nested data categorization. A predefined structure `hierarchicalFacets` organizes categories and their sub-categories. The `renderHierarchicalFacets` function iteratively generates UI components for each facet and its nested options, connecting them with the `handleFacetToggle` function for selection management.