DEV Community

Anil
Anil

Posted on

How to use search filter in React.js

To implement a search filter in React, you can follow these basic steps:

  1. State Setup Create a state to hold your data and another state to hold the search input.
const [data, setData] = useState(initialData);
const [searchInput, setSearchInput] = useState('');
Enter fullscreen mode Exit fullscreen mode
  1. Handling Search Input Update the search input as the user types in the search box.
const handleSearch = (e) => {
  setSearchInput(e.target.value);
};
Enter fullscreen mode Exit fullscreen mode
  1. Filtering the Data Use the filter() method to filter the data based on the search input.
const filteredData = data.filter(item =>
  item.name.toLowerCase().includes(searchInput.toLowerCase())
);
Enter fullscreen mode Exit fullscreen mode
  1. Displaying the Results Map through the filtered data and display the results.
return (
  <div>
    <input type="text" placeholder="Search..." onChange={handleSearch} />
    <ul>
      {filteredData.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Example Code
Here's a complete example based on the above explanation:

import React, { useState } from 'react';

const SearchFilter = () => {
  const initialData = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
    { id: 3, name: 'Peter Parker' },
  ];

  const [searchInput, setSearchInput] = useState('');

  const filteredData = initialData.filter(item =>
    item.name.toLowerCase().includes(searchInput.toLowerCase())
  );

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        onChange={(e) => setSearchInput(e.target.value)}
      />
      <ul>
        {filteredData.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default SearchFilter;
Enter fullscreen mode Exit fullscreen mode

For more detailed tutorials, you can explore:

freeCodeCamp's Guide​(
freeCodeCamp
)
KindaCode's Tutorial​(
KindaCode
)

Top comments (0)