Home > Mobile >  Filtering items by category in a React.js search component"
Filtering items by category in a React.js search component"

Time:01-27

I am trying to implement a search feature in my React.js application that allows users to search for items within a specific category. I have a list of items and a list of categories, and I want the search results to only include items that belong to the selected category.

Here is the code for my Search component where I am trying to filter the items:

import React, { useState } from 'react';

const Search = ({ items, categories, selectedCategory }) => {
  const [searchResults, setSearchResults] = useState([]);

  const handleSearch = (e) => {
    const searchTerm = e.target.value;
    const filteredItems = items.filter((item) => {
      return item.category === selectedCategory && item.name.includes(searchTerm);
    });
    setSearchResults(filteredItems);
  }

  return (
    <div>
      <select onChange={(e) => setSelectedCategory(e.target.value)}>
        {categories.map((category) => (
          <option key={category.id} value={category.id}>{category.name}</option>
        ))}
      </select>
      <input type="text" onChange={handleSearch} />
      <ul>
        {searchResults.map((result) => (
          <li key={result.id}>{result.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default Search;

I've been trying to use the filter method to filter the items based on their category, but I'm not sure how to properly implement it. I've already tried passing the selectedCategory as a prop to the Search component and using it in the filter method, but it doesn't seem to be working. The handleSearch function is called when the user types into the input field, it is supposed to filter the items based on the selected category and the search term entered by the user.

Can anyone help me understand what I'm doing wrong here and how to correctly filter the items based on the selected category in my React.js application? Any help would be greatly appreciated.

CodePudding user response:

Try this code:

import React, { useState } from 'react';

const Search = ({ items, categories }) => {
    const [searchResults, setSearchResults] = useState([]);
    const [selectedCategory, setSelectedCategory] = useState(1);

    const handleSearch = (e) => {
        const searchTerm = e.target.value;
        if (searchTerm) {
            const filteredItems = items.filter((match) => {
                const regex = new RegExp(`${searchTerm}`, 'gi');
                return match.name.match(regex) && match.category === Number(selectedCategory);
            });
            setSearchResults(filteredItems);
            return;
        }
        setSearchResults([]);
    };

    return (
        <div>
            <select onChange={(e) => setSelectedCategory(e.target.value)}>
                {categories.map((category) => (
                    <option key={category.id} value={category.id}>{category.name}</option>
                ))}
            </select>
            <input type="text" onChange={handleSearch} />
            <ul>
                {searchResults.length > 0 && searchResults.map((result) => (
                    <li key={result.id}>{result.name}</li>
                ))}
            </ul>
        </div>
    );
};

export default Search;

You have to select some category before search anything, or you can set default value for the selected category.

dont put the selectedCategory as a props, but put it as a state. Because your option for selecting category in the Search Component, not other component.

  • Related