I'm trying to setup filtering by checkbox in React.
What I want to happen is:
- User navigates to products where all products on displayed on page load.
- User selects checkbox and filtered products are displayed.
- De-selecting the checkbox will return all products again.
What currently happens is:
- User navigates to products, no products are displayed.
- User selects checkbox, filtered products are returned.
- Use deselects checkbox, all products are returned.
So it's nearly there, but something is missing for the initial page load, can anyone please advise what I've missed?
Example Data =
console.log(checkedInputs) = Object { 35: true }
console.log(Item) = Object { itemID: "5190", systemSku: "item", defaultCost: "78.95", avgCost: "78.95", discountable: "true", tax: "true", archived: "false", itemType: "default", serialized: "false", description: "item", … }Object { itemID: "5191", systemSku: "item", defaultCost: "142.95", avgCost: "142.95", discountable: "true", tax: "true", archived: "false", itemType: "default", serialized: "false", description: "item", … }
On initial page load checkedInputs =
console.log(checkedInputs = Object { })
Thanks!
Products.jsx
const Products = (props) => {
const { Item } = props.items
const { Category } = props.categories
const [checkedInputs, setCheckedInputs] = useState({})
const handleInputChange = (event) => {
setCheckedInputs({ ...checkedInputs, [event.target.value]: event.target.checked })
}
useEffect(() => {
console.log('Checked Inputs', checkedInputs)
}, [checkedInputs])
return (
<Layout>
<div className="flex mx-96">
<div className="w-1/4">
<ProductFilter category={Category} handleInputChange={handleInputChange} checkedInputs={checkedInputs} />
</div>
<div className="w-3/4">
<div className="lg:grid grid-cols-3 gap-2 lg:my-12 lg:justify-center">
{Item.map(item => {
for (const [key, value] of Object.entries(checkedInputs)) {
if (!checkedInputs || Object.keys(checkedInputs).every(value => checkedInputs[value] === false)) {
return <ProductCard item={item} key={item.itemID} />
}
if (value === true) {
if (item.categoryID === key) {
console.log(item)
return <ProductCard item={item} key={item.itemID} />
}
}
}
})}
</div>
</div>
</div>
</Layout>
)
}