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
)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay