Savio Martin

Create a Search Filter in React from Scratch 🔎

Created June 26, 2021

Hello Folks 👋

This is Savio here. I'm young dev with an intention to enhance as a successful web developer. I love building web apps with React. I have proved my superiority in frontend technologies.

Today, Let's learn how you can create a well-efficient search filter in React ✌️. So, let's start!


Create React App

First of all, we first have to create a react app. You know it!

npx create-react-app search-filter-app

This will create you a normal react app. You can start the server by npm start. Now, let's have a look at our folder structure 🥁 Make sure, you have this files ready 🤗

src/
├── App.css
├── App.js
└── index.js

Lets start with App.js, we can use https://jsonplaceholder.typicode.com/ API, to get some fake posts data. First, lets create a useState hook 👀

const [data, setData] = useState([]);

Now, lets create a useEffect with no dependency that should load only once. 💪

useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

Now, lets render our app, we just need an input that acts as our search bar and then, lets map through the data ✌️

<div className="App">
    <input type="text" placeholder="Search name"  />
    {data.map((post, key) => {
          return (
            <p className="blog" key={key}>
              {post.title}
            </p>
           );
     })}
</div>

Now, lets next step is to handle the search, for that, I'm setting a new useState hook called searchTerm 🍻

const [searchTerm, setSearchTerm] = useState("");

And now, lets handle the onChange event of our input 👇

<input type="text" placeholder="Search name" value={searchTerm} onChange={(e)=> setSearchTerm(e.target.value)}
/>

And lastly, lets create a small logic of handling the search, lets use filter for it, we're first converting it to toLowerCase() and then check if it is same as searchTerm, and then map through it. Lets see how I made it work 👇

{
  data
    .filter((val) => {
      if (searchTerm === "") {
        return val;
      } else if (
        val.title.toLowerCase().includes(searchTerm.toLowerCase())
      ) {
        return val;
      }
    })
    .map((post, key) => {
      return ( 
        <p className="blog" key={key}>
              {post.title}
        </p>
      );
    })
   }
}

that's it 🎉, you made it work, it works just fine, lets add some css to make it better 👇 Add this to App.css

input {
  padding: 10px;
  border: 1px solid #111;
  width: -webkit-fill-available;
  border-radius: 5px;
}
.blog {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

Now, everything is over, time to test it, Here it goes, it works like a charm 💖 Congrats 🥳

ezgif-6-c3f8a6edeb05.gif


👀 Wrapping Up

Yeah, that's a wrap. Hope you enjoyed the article. Do not hesitate to share your feedback. I am on Twitter @saviomartin7. Give a follow!

Follow me on Github @saviomartin, Don't miss my amazing projects! 💯

Feedbacks are greatly appreciated! 🙌 Have an amazing day!

🌎 Lets connect