You are currently viewing How to create search filter in react.js [in 2022]?

How to create search filter in react.js [in 2022]?

Hello Everyone,

In this article, we will see how to create the search filter in react.js. This is one of the most frequently asked interview questions for intermediate and experienced react developers.

Let’s implement it together. I advise opening the vs code editor and code along.

Before this, let me show you the final look at the search filter that we are going to build. 

This is hosted on GitHub pages and can be checked at – https://ajayv1.github.io/search-filter-in-reactjs/

search filter in react.js

Implementation of search filter in react.js

Step 1. Create folder and init react repo

				
					mkdir search-filter
npx create-reate-app .

// or

npx create-reate-app search-filter
				
			

Both approaches are acceptable. Sometimes I forget to create the repo directly from react in that case I use the 2nd line npx create-react-app .

Step 2. Add logic in app.js file

				
					import './App.css';
import { useEffect, useState } from 'react';

function App() {
  const [users, setUsers] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [filteredUser, setFilteredUser] = useState([]);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const data = await fetch('https://jsonplaceholder.typicode.com/users');
        const userData = await data.json();
        
        setUsers(userData);
      } catch (err) {
        console.log(err);
      }
    };

    fetchUser();
  }, []);

  useEffect(() => {
    if (searchText.length) {
      const filterUsers = users.filter((user) => {
        return (user.name).toLowerCase().includes(searchText.toLowerCase());
      });

      setFilteredUser(filterUsers);
    } else {
      setFilteredUser([]);
    }
  }, [searchText, users]);

  return (
    <div className="container">
      <h1 className='title'>Search Filter in react <span>( by weekendtutorial.com )</span></h1>
      <input className='search' type="text" placeholder='search user' value={searchText} onChange={(e) => setSearchText(e.target.value)}/>
      <ul className='userList'>
        {
          filteredUser.length ? 
            filteredUser.map((user) => <li className='userListItem' key={user.id}>{user.name}</li>) :        
            users.map((user) => <li className='userListItem' key={user.id}>{user.name}</li>)
        }
      </ul>
      
    </div>
  );
}

export default App;

				
			

Let me explain the above code. We have to maintain 3 states – one for the user list, one for search text, and one for the filtered user list.

We have used https://jsonplaceholder.typicode.com/users for the user list. This gives us a list of dummy users.

In the first useEffect, we make a GET request to fetch this user list and set the user’s state.

In the second useEffect, whenever the search text changes, we are filtering the list of users which contains the search text in their username.

Lastly, we are displaying the filtered users or the complete users based on the search text.

Step 3. Add CSS in app.css and index.css file

Global styling like HTML, body, list style none, etc is kept in the index.css file.

Complete logic and jsx are written within the App.js file so all styling is also written in the app.css file. 

  • used a min-height of 300px for the container to avoid the list jumping on the search
				
					/* index.css */

@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');

html, * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  width: 100vw;
  height: 100vh;
  background-color: #282c34;
  margin: 0;
  font-family: 'Roboto', sans-serif;
  color: #eee;
}

ul {
  list-style: none;
}
				
			
				
					/* app.css */

.container {
  min-height: 300px;
  width: 30%;
  margin: 20px auto;
  overflow-y: auto;
}

.title {
  font-size: 22px;
  color: aquamarine;
  margin: 2rem 0;
}

.title > span {
  font-size: 14px;
}

.search {
  width: 100%;
  padding: 10px;
  border: 1px solid black;
  margin: 10px 0;
}

.search:focus {
  outline: none;
}

.userList {
  width: 100%;
  min-height: calc(100vh - 37.5px);
}

.userListItem:first-child {
  border-top: 1px solid white;
}

.userListItem {
  border-left: 1px solid white;
  border-right: 1px solid white;
  border-bottom: 1px solid white;
  padding: 10px;
}
				
			

I would recommend checking out the below book to solidify your react.js knowledge.

Please share the articles on –

Facebook
Twitter
LinkedIn
Subscribe

The latest tips and news from the industry straight to your inbox!

Join 30,000+ subscribers for exclusive access to our monthly news and tutorials!