How do I add more fields when searching?

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:

  1. it will show all of the products with a category of ML upon entering in the search field.
  2. It will show all of the products with a size of M upon entering m or M in the search 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) => {

One possible approach:

  useEffect(() => {
    let x = [...products]; // Actually you don't need this
    x = x.filter((y) => {
      const key = searchKey.toLocaleLowerCase()
      const values = ['prodName', 'size', 'cat']
      return values.some(val => y[val]
        .toLocaleLowerCase()
        .includes(key))
    });
    setSearchList(x);
  }, [searchKey]);
1 Like

Thank you for the help

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.