Guvi-blog-logo

Build a Search Component in React [just in 3 simple steps]

search component in react

Getting Started

If you’re building an app that has a lot of data whether in the form of a list or in any other form and you want the users to be able to search and get filtered results, then we need to create a way for the users to be able to find data they’re searching for from the list easily. To cover this solution, adding a search and filter component to a react application can be a great way to improve the user experience by making it easier & time saving for users to find what they are looking for. In this blog post, we will discuss how to add a search and filter component to a React application.

What is search component

Search bars or fields are a great way of helping users find what they need on the website. Not only this, they provide good analytics if we want to keep track of what our visitors are searching for on the website. Here we are going to use react to build a search bar that filters and displays data as the user types. With the help of React hooks and the JavaScript map and filter array methods, the result displayed is responsive with a functional search box. 

Let’s now see how does a search component works in react.

How does Search works in react

The search component in React works by allowing users to enter search terms into an input field and then filtering the results based on the search terms. This can be done by setting up an event handler for the input field to listen for changes and then using the search terms to filter the results. This can also be done with the help of JavaScript or a library like React-SearchBox but for now let’s do this manually with the help of hooks and other things.

To demonstrate how the search works in react, we’ll be using the mock data to create a list provided freely by https://jsonplaceholder.typicode.com/ in JSON format. We are going to use the user’s endpoint from that API i.e., https://jsonplaceholder.typicode.com/users. The JSON data that comes from API looks like below:

JSON data

Don’t get confused from the above photo, it’s just an array of data displayed in JSON format. We will be using some of the data from the given array and display it in our react app for the purpose of searching and filtering.

Creating a react app from scratch

Before moving onto the steps of adding a search component, first we need to have a react application. To create a new react application we are going to use create-react-app as it is the best way to create a single-page application.

npx create-react-app demo

cd demo

npm start

Steps to add a Search functionality in react

Fetching Data

To fetch data in react we use JavaScript Fetch API. It works by taking one argument and the path from where the data is to be fetched and then returning a promise in an JSON object.

In our previous blog we have already discussed How to Fetch and Display data using API so we are not going to discuss that again here in detail.

App.js file

function App() {

  const url = "https://jsonplaceholder.typicode.com/users";
  const [data, setData] = useState([]);

  const fetchData = () => {
    return fetch(url)
      .then((res) => res.json())
      .then((d) => setData(d));
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    ...
  );
}

export default App;

Above, we have used the JavaScript Fetch API to fetch the data by making a request to the endpoint and then storing the returned data into data state using setData(d) and used the useEffect() hook to make the function run every time the page loads.

Displaying Data

Now we have the data, so we are going to display it. In the App.js file, add the following code in the return() statement of the function.

function App() {

  const url = "https://jsonplaceholder.typicode.com/users";
  const [data, setData] = useState([]);

  const fetchData = () => {
    return fetch(url)
      .then((res) => res.json())
      .then((d) => setData(d));
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (

    <center>
        {data.map((dataObj) => {
          return (
            <div className="box">
              <div class="card">
                <div class="category">@{dataObj.username} </div>
                <div class="heading">
                  {dataObj.name}
                  <div class="author">{dataObj.email}</div>
                </div>
              </div>
            </div>
          );
        })}

      </center>

  );

}

export default App;

Here, we display three things: username, email, and name, from the data fetched from users API endpoint.

Creating a Search component in React

So, now we have created our list of data, let’s add the search component and see how the searched data is going to be returned.

Step 1: Creating an Input field

The first step is to create an input field. It allows the user to enter a search query just by typing into the search field.

<div className="input-box">

         <input

             type="search"

             name="search-form"

             id="search-form"

             className="search-input"

              onChange={(e) => setSearchQuery(e.target.value)}

             placeholder="Search user"

         />

       </div>

With the help of onChange event handler, anytime the value of the input field changes we set the value to searchQuery using the useState hook.

Step 2: Getting search parameters

Here, we are getting the search parameters from the data returned from the API.

const search_parameters = Object.keys(Object.assign({}, ...data));

Step 3: Function to query the search

Next we need to use that searchQuery to search and filter out the data returned from our API.

const search_params = Object.keys(Object.assign({}, ...data));

  function search(data) {

    return data.filter((data) =>

      search_params.some((param) =>

        data[param].toString().toLowerCase().includes(searchQuery)

      )

    );

  }

Let’s understand the above function. First we have created a function search() that takes the data as an argument. Using the Array.filter() and Array.some() methods we are checking if any of our Search query parameters include the value of our query includes(searchQuery).

Step 4: Displaying the search results

As the last step, we are going to use the data returned from the search(data) function to display our users list. 

{search(data).map((dataObj) => {

          return (

            <div className="box">

              <div class="card">

                <div class="category">@{dataObj.username} </div>

                <div class="heading">

                  {dataObj.name}

                  <div class="author">{dataObj.email}</div>

                </div>

              </div>

            </div>

          );

        })}

And finally your App.js file should look like below.

import "./App.css";

import React, { useEffect, useState } from "react";

function App() {

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

  const fetchData = () => {

    return fetch("https://jsonplaceholder.typicode.com/users")

      .then((res) => res.json())

      .then((d) => setData(d));

  };

  useEffect(() => {

    fetchData();

  }, []);

  const [query, setQuery] = useState("");

  const search_parameters = Object.keys(Object.assign({}, ...data));

  function search(data) {

    return data.filter((data) =>

      search_parameters.some((parameter) =>

        data[parameter].toString().toLowerCase().includes(query)

      )

    );

  }

  return (

    <div className="container">

      <center>

        <h1>Search component in ReactJS</h1>

      </center>

      <div className="input-box">

        <input

          type="search"

          name="search-form"

          id="search-form"

          className="search-input"

          onChange={(e) => setQuery(e.target.value)}

          placeholder="Search user"

        />

      </div>

      <center>

        {search(data).map((dataObj) => {

          return (

            <div className="box">

              <div class="card">

                <div class="category">@{dataObj.username} </div>

                <div class="heading">

                  {dataObj.name}

                  <div class="author">{dataObj.email}</div>

                </div>

              </div>

            </div>

          );

        })}

      </center>

    </div>

  );

}

export default App;

Output

Search component in reactjs

We often handle the search query functionality from the back end side by passing search query parameters in the API endpoint. And now we have seen how it can be handled from the front end side. 

Now that you’ve added a search component to your React application, you can easily allow your users to search for specific items or information. With a few simple steps, you can add a powerful and useful search component to your application.

Conclusion

In this blog, we learned how to add a search component to a react application and saw how the data is filtered from a bunch of data. Search component helps the users in finding the important information on the website quickly and also helps them in navigating to different pages. 

Hope you learned a lot from this blog but don’t stop your learning in React.js here. Become a Full Stack Developer by joining our industry-leading project-based career program on Full Stack Development  offered by Zen Class which provides you with 100% job placement support, globally recognized certification, mentors support from top product based companies, and many more. 

Contact Form

By clicking 'Submit' you Agree to Guvi Terms & Conditions.

Our Learners Work at

Our Popular Course

Share this post

Author Bio

Tarun Singh
Tarun Singh
Tarun Singh is a Front-End Developer and Technical Writer with 2+ years of relevant experience. He is passionate about creating appealing and user-friendly apps and in writing technical articles. His expertise lies in ReactJS.

Our Live Classes

Learn Javascript, HTML, CSS, Java, Data Structure, MongoDB & more
Learn Python, Machine Learning, NLP, Tableau, PowerBI & more
Learn Selenium, Python, Java, Jenkins, Jmeter, API Testing & more

UX Processes, Design systems, Responsive UI, & more with placement assistance.

Hey wait, Don’t miss New Updates from GUVI!

Get Your Course Now

Related Articles