Last active
May 2, 2022 07:08
-
-
Save pushkar100/39888f4f3df8fc5802de76b27ef6999c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer } from "react"; | |
// 1. REDUCER + HOOK: | |
const initialProductSearchFilterState = { | |
product: "", | |
colors: [] | |
}; | |
const productSearchFilterReducer = (state, action) => { | |
switch (action.type) { | |
case "product": | |
return { | |
...state, | |
product: action.payload | |
}; | |
case "addColor": | |
return { | |
...state, | |
colors: [...state.colors, action.payload] | |
}; | |
case "removeColor": | |
return { | |
...state, | |
colors: state.colors.filter((c) => c !== action.payload) | |
}; | |
default: | |
return state; | |
} | |
}; | |
// 2. USING THE HOOK IN A COMPONENT: | |
const useProductSearchFilter = () => { | |
const [{ product, colors }, dispatch] = useReducer( | |
productSearchFilterReducer, | |
initialProductSearchFilterState | |
); | |
const selectProduct = (product) => | |
dispatch({ type: "product", payload: product }); | |
const selectColors = (color, add) => | |
add | |
? dispatch({ | |
type: "addColor", | |
payload: color | |
}) | |
: dispatch({ | |
type: "removeColor", | |
payload: color | |
}); | |
return { | |
product, | |
colors, | |
selectProduct, | |
selectColors | |
}; | |
}; | |
const ProductSearchFilter = ({ | |
products = [], | |
colors = [], | |
sizes = [], | |
onSearch = () => {} | |
}) => { | |
const { | |
product, | |
colors: selectedColors, | |
selectProduct, | |
selectColors | |
} = useProductSearchFilter(); | |
return ( | |
<> | |
<div> | |
{products.map((product) => ( | |
<label for={product}> | |
<input | |
type="radio" | |
name="product" | |
value={product} | |
onChange={(e) => e.target.checked && selectProduct(product)} | |
/> | |
{product} | |
</label> | |
))} | |
</div> | |
<div> | |
{colors.map((color) => ( | |
<label for={color}> | |
<input | |
type="checkbox" | |
name="selectedcolors" | |
value={color} | |
onChange={(e) => selectColors(color, e.target.checked)} | |
/> | |
{color} | |
</label> | |
))} | |
</div> | |
<button onClick={() => onSearch(product, selectedColors)}>Search</button> | |
</> | |
); | |
}; | |
export default ProductSearchFilter; | |
/** | |
* Usage: | |
<ProductSearchFilter | |
products={["t-shirt", "shorts", "jeans"]} | |
colors={["red", "white", "black"]} | |
/> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment