Every website or web app probably needs search functionality for a better user experience. There are a bunch of packages available to implement a search bar in React projects, but they are not flexible, making them less customizable.

In this tutorial, we will look at how to make a search component in React with the help of React hooks.

Project setup

Get started by creating react app on your machine or open your browser and visit react.new

A new CodeSandbox environment will open with React project setup.

Fetch data

For the search component, we will fetch the country’s name from an API and display them. Then we will add the search input where users can easily search for the countries. Here’s the API endpoint from which we will fetch data: https://restcountries.com/v3.1/all.

Learn how to fetch data in React here.

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

function App() {
  const [data, setData] = useState([]);

  const fetchData = () => {
    fetch("https://restcountries.com/v3.1/all")
      .then((res) => res.json())
      .then((result) => {
        setData(result);
        console.log(result);
      });
  };

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

  return (
    <div>
      {data.map((res) => (
        <h1>{res.name.common}</h1>
      ))}
    </div>
  );
}

export default App;

First, we are using the useState hook for storing all the data we get from an API. Next, we have the fetchData function which fetches the data from an API and updates our initial state.

You can check the data in the console.

Then we have the useEffect hook which calls the fetchData function only on the initial render.

Inside JSX we are mapping our data state to display the country’s name from API.

Implementing Search feature

To implement the search logic, we will again make use of the useState hook which holds the query value to an empty string and we have a setQuery function that will update our query to a value that the user will enter in the input field.

import React, { useState, useEffect } from "react";
import "./app.css";

function App() {
  const [data, setData] = useState([]);
  const [query, setQuery] = useState("");

  const fetchData = () => {
    fetch("https://restcountries.com/v3.1/all")
      .then((res) => res.json())
      .then((result) => {
        setData(result);
        console.log(result);
      });
  };

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

  return (
    <div>
       setQuery(event.target.value)}
      />
      {data
        .filter((res) => {
          if (query === "") {
            return res;
          } else if (
            res.name.common.toLowerCase().includes(query.toLowerCase())
          ) {
            return res;
          }
        })
        .map((res) => (
          <div>
            <h1>{res.name.common}</h1>
            <img src="{res.flags.png}" alt="logo" width="{200}" height="{100}" />
          </div>
        ))}
    </div>
  );
}

export default App;

Inside JSX we have a filter function that checks if the user-entered query is matched to the data that we have displayed. In short, we are checking if the country name matches the value entered in the input field.

That’s it. How easy was that?

You can run your react app and see how the search component works:

Conclusion

The search bar is a feature that every website should have. We learned how to create a search bar from scratch with the help of React hooks. You can add some CSS to it and make the search bar look better. Go ahead and customize it as per your needs.

Thank you so much for reading this tutorial.

Feel free to comment if you have any questions or If you have suggestions. If you want to request any article for a particular topic contact through the about page. I would love to hear from you.

👋 Hey, I'm Pratham Bhagat
I simplify complex web development topics. My curiosity leads me to learn about various technologies, and my love for writing helps me to impart my knowledge for the same.

💬 Leave a comment

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.