Reputation: 3854
This is my redux state :
products: [
{
id: 1,
name: 'Ps4',
price: 4500000,
number: 0,
inCart: false,
category: 'electronics',
brand: 'sony',
subCategory: 'game',
img: 'ps4',
stockNumber: 4,
off: false,
offPrice: null
},
{
id: 24,
name: 'Gucci',
price: 7210000,
number: 0,
inCart: false,
category: 'outfit',
brand: 'gucci',
subCategory: 'bag',
img: 'gucci-bag',
stockNumber: 2,
off: false,
offPrice: null
},
{
id: 10,
name : 'Phone',
price: 5800000,
inCart: false,
category: 'electronics',
brand: 'samsung',
subCategory: 'mobile',
img: 'a70',
stockNumber: 3,
off: true,
offPrice: 6000000
}
]
And I loop through and display in component the way they are
{props.products.map((item) => {
return <div key={item.id}>{item.name}</div>
)}
Now I want to filter them by a multiple input checkboxes so when they're checked it filters them and displays only ones with stockNumber > 2 for example or multiple conditions and when it's unchecked it just gets the whole products .
<input onChange={()=>handleFilter('filter by stockNumber > 3')} />
<input onChange={()=>handleFilter('filter by inCart === false')} />
<input onChange={()=>handleFilter('filter by price > 200')} />
How can I achieve this and how many functions will make this work ?
Upvotes: 0
Views: 198
Reputation: 32078
You should change the logic a bit, in pseudo-js something like this:
<input type="checkbox" onChange={toggleFilter1} />
<input type="checkbox" onChange={toggleFilter2} />
<input type="checkbox" onChange={toggleFilter3} />
const filter1Enabled = input1Ref.checked // or state.input1Checked
// ...
const filteredProducts = props.products.filter(item => {
if (filter1Enabled && doesntPass1(item)) return false
if (filter2Enabled && doesntPass2(item)) return false
if (filter3Enabled && doesntPass3(item)) return false
return true
})
return (
<>
{ filteredProducts.map(item => <div key={item.id}>{item.name}</div>) }
</>
)
So basically, you must keep track of which filters are enabled and then apply them in the filter one by one.
Upvotes: 1