I have this functionality to search the product. However, I could only search the name of the product.
Problem: How can I implement a search where it will allow me to search either the product name, size, or category?
For now, I was able to search and display the products according to what product name was entered in the search
field.
For example:
- it will show all of the products with a category of ML upon entering in the
search
field. - It will show all of the products with a size of
M
upon enteringm
orM
in thesearch
field.
codesandbox: Add to Cart Sampled 2 - CodeSandbox
Codes:
export default function App() {
const [cartItems, setCartItems] = useState([]);
const [searchList, setSearchList] = useState([]);
const [searchKey, setSearchKey] = useState("");
useEffect(() => {
let x = [...products];
x = x.filter((y) => {
return y.prodName
.toLocaleLowerCase()
.includes(searchKey.toLocaleLowerCase());
});
setSearchList(x);
}, [searchKey]);
const handleAdd = (id, name, size, cat, color) => {
console.log("add", id, name, size, cat, color);
const productExist = cartItems.find(
(item) => item.id === id && item.color === color
);
if (productExist) {
setCartItems(
cartItems.map((item) =>
item.id === id && item.color === color
? { ...productExist, quantity: productExist.quantity + 1 }
: item
)
);
} else {
setCartItems([...cartItems, { id, name, size, cat, color, quantity: 1 }]);
}
};
// const handleAdd = (item) => {