How to create a Filter/Search List in React (updated)

Updated: March 6, 2024 By: A Goodman 18 comments

This article walks you through a complete example of making a filter (searchable) list in React. We’ll use the most recent stable version of React (18.3) as well as use functional components and hooks.

The Example

Let’s say we have a list of users. Our job is to filter (search) some users by their names.

We’ll use the filter() and startsWith() methods (just two Javascript methods) to find out users whose names match the text entered in the search box. We also use the toLowerCase() method to make it case-insensitive.

When the search box is empty, all users will be displayed.

Preview

Javascript code

To make sure we start at the same place, you should create a brand new React project:

npx create-react-app kindacode-example

Here’s the full source code in src/App.js:

import React, { useState } from 'react';

import './App.css';

// This holds a list of some fiction people
// Some  have the same name but different age and id
const USERS = [
  { id: 1, name: 'Andy', age: 32 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Tom Hulk', age: 40 },
  { id: 4, name: 'Tom Hank', age: 50 },
  { id: 5, name: 'Audra', age: 30 },
  { id: 6, name: 'Anna', age: 68 },
  { id: 7, name: 'Tom', age: 34 },
  { id: 8, name: 'Tom Riddle', age: 28 },
  { id: 9, name: 'Bolo', age: 23 },
];

function App() {
  // the value of the search field 
  const [name, setName] = useState('');

  // the search result
  const [foundUsers, setFoundUsers] = useState(USERS);

  const filter = (e) => {
    const keyword = e.target.value;

    if (keyword !== '') {
      const results = USERS.filter((user) => {
        return user.name.toLowerCase().startsWith(keyword.toLowerCase());
        // Use the toLowerCase() method to make it case-insensitive
      });
      setFoundUsers(results);
    } else {
      setFoundUsers(USERS);
      // If the text field is empty, show all users
    }

    setName(keyword);
  };

  return (
    <div className="container">
      <input
        type="search"
        value={name}
        onChange={filter}
        className="input"
        placeholder="Filter"
      />

      <div className="user-list">
        {foundUsers && foundUsers.length > 0 ? (
          foundUsers.map((user) => (
            <li key={user.id} className="user">
              <span className="user-id">{user.id}</span>
              <span className="user-name">{user.name}</span>
              <span className="user-age">{user.age} year old</span>
            </li>
          ))
        ) : (
          <h1>No results found!</h1>
        )}
      </div>
    </div>
  );
}

export default App;

CSS code

Below’s the full source code in src/App.css:

.container {
  padding-top: 30px;
  width: 300px;
  margin: auto;
}

.input {
  padding: 5px 15px;
  width: 300px;
}

.user-list {
  margin-top: 30px;
}

.user {
  list-style: none;
  margin: 10px 0;
  padding: 10px;
  background: #eee;
  display: flex;
  justify-content: space-between;
}

.user-id {
  color: red;
  margin-right: 20px;
}

.user-name {
  color: blue;
}

.user-age {
  margin-left: auto;
}

Conclusion

Congratulation! At this point, you should get a better understanding and feel more comfortable when working with a filter/search list in React. Continue learning and pushing forward by taking a look at the following articles:

You can also check our React topic page and React Native topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
18 Comments
Inline Feedbacks
View all comments
Rajesh
Rajesh
9 months ago

heplfull article ………

xyeres
xyeres
1 year ago

Thanks for the article! Using Array.prototype.includes() is much more concise, if the query string is empty (“”) then it matches all records in the array. Else it matches partial strings. Less logic to worry about.

Zane
Zane
1 year ago

I tried applying this to my code but when it first renders the list is empty instead of showing everything. My code base takes the filteredNames and passes them into another component that renders them in a table. They only appear once I start using the search bar. What am… Read more »

Joseph
Joseph
1 year ago
Reply to  Zane

I have the same problem too, nothing shows unless I start typing something in the search bar

Joseph
Joseph
1 year ago
Reply to  A Goodman

Nothing seems to be wrong with the code, I used a conditional operator to display all the contents and if that’s false, then just display filtered ones if true… Solved my problem…

mohamed
mohamed
1 year ago

Thank you, man 🙏

sunnystark
sunnystark
1 year ago

we can compress this code like this import React, { useState } from “react“; import { render } from “react-dom“; const cities = [“agra“, “kanpur“, “Ahamdabad“, “noida“]; const App = () => { const [filterData, setFilterData] = useState(cities); // const [name, setName] = useState(“”); const handleChange = (e) => {… Read more »

Maravilloso
Maravilloso
2 years ago

this code is so simple and it works in a stable!

Felistus
Felistus
2 years ago

Thank you so much for the example. It helped me solve the filter search challenge I was having.

Darwin
Darwin
2 years ago

i want to change the code to search for streetname. However, seems the code is not working. Can you have a look ?
https://codesandbox.io/s/compassionate-swanson-u504c?file=/src/App.js&fbclid=IwAR1vBrb7j7RIRNDZ94WEE1nL4zTc8Y3KvVjY5FNuuNzMVdYNJ2w2nxqOpRE

Paul
Paul
2 years ago

I think we should improve this by using useEffect so it can search from any alphabet that those names have and render the names from the array objects

Gerald Hyuha
Gerald Hyuha
2 years ago

where is the index html file?????

Related Articles