I want to filter my product by category, type, and brand. I found a video from youtube and follow the tutorial but I only can filter by category or type or brand at once time, and also if after I click on "Filter by Category "test" then I click on other filter it display nothing.
ScreenShot of my website
My code
`
const filterResult = (catItem) => {
const result = product.filter((product) => {
return product.category === catItem
});
setProduct(result);
}
<div>
<h3 onClick={ () => {filterResult('test')}}>Filter by Category "test"</h3>
<h3 onClick={ () => {filterResult('abc')}}>Filter by Category "abc"</h3>
<h3 onClick={ () => {filterResult('efg')}}>Filter by Category "efg"</h3>
<h3 onClick={ () => {filterResult('belden')}}>Filter by Brand "belden"</h3>
<h3 onClick={ () => {filterResult('bluguard')}}>Filter by Brand "bluguard"</h3>
<h3 onClick={ () => {filterResult('audio')}}>Filter by Type "audio"</h3>
<h3 onClick={ () => {filterResult('wifi ')}}>Filter by Type "wifi"</h3>
<h3 onClick={lowToHigh}>Sort By Low to High</h3>
<h3 onClick={highToLow}>Sort By High to Low</h3>
</div>
So how do I filter my product by category, type and brand at same time?
CodePudding user response:
You'll need to put the filters into state. Either have a different state for each possible filter, or use a single state with an object. Then use that state as the basis for the filtered products.
You probably don't want to do setProduct(result);
, because that'll overwrite the existing state; you won't be able to get back to the original products. Instead of having a state for the filtered products, filter them when rendering.
const [filters, setFilters] = useState({
category: '',
brand: '',
type: '',
});
const makeFilter = (property, newFilterValue) => () => {
setFilters({
...filters,
[property]: newFilterValue,
});
};
The utility function makeFilter
above makes it easy to concisely create a click handler that adds a filter.
<h3 onClick={makeFilter('category', 'test')}>Filter by Category "test"</h3>
<h3 onClick={makeFilter('category', 'abc')}>Filter by Category "test"</h3>
And to render:
products // original state
.filter(prod =>
prod.category.includes(filters.category) &&
prod.brand.includes(filters.brand) &&
prod.type.includes(filters.type)
)
.map(product => // JSX to render product, as desired