Build a Search Bar Component in React

Building React applications over a decade ago, one of the most common requests from clients was to add a search feature.

It sounds simple, but a search bar can drastically improve the user experience. Whether you’re building an e-commerce site, a blog, or a data-heavy dashboard, users need a quick way to find what they’re looking for.

In this guide, I’ll walk you through how to create a search bar component in React. I’ll cover multiple methods, provide full code examples, and explain each step in plain English. By the end, you’ll have a reusable search bar that you can drop into any React project.

Why Add a Search Bar?

A search bar isn’t just a “nice-to-have” feature; it’s essential. Think about how you use Amazon, Netflix, or even your email inbox. Without a search option, finding content would feel like digging through a haystack.

In React, building a search bar is easy once you understand how to manage state and filter data dynamically. Let’s dive into the methods I use most often.

Method 1 – Basic Search Bar with State and Filter

The simplest way to create a search bar in React is to use the useState hook and JavaScript’s built-in filter method.

Here’s the complete code:

import React, { useState } from "react";

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

  const data = [
    "New York",
    "Los Angeles",
    "Chicago",
    "Houston",
    "Phoenix",
    "San Diego",
    "Dallas",
    "San Jose",
  ];

  const filteredData = data.filter((item) =>
    item.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <div style={{ padding: "20px", maxWidth: "400px", margin: "auto" }}>
      <input
        type="text"
        placeholder="Search for a city..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        style={{
          width: "100%",
          padding: "10px",
          fontSize: "16px",
          marginBottom: "10px",
        }}
      />
      <ul>
        {filteredData.map((city, index) => (
          <li key={index}>{city}</li>
        ))}
      </ul>
    </div>
  );
};

export default SearchBarBasic;

I have executed the above example code and added the screenshot below.

Build a Search Bar Component in React

Explanation:

  • I used useState to track the user’s input.
  • Then I applied a filter to only show results that match the query.

This method works great for small datasets like city names or product lists.

Method 2 – Search Bar with API Data (Using Axios)

Most real-world apps don’t just filter static arrays; they fetch data from APIs. Let’s build a search bar that interacts with an API.

Here’s the full code:

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

const SearchBarAPI = () => {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);

  useEffect(() => {
    if (query.length > 2) {
      axios
        .get(`https://api.datamuse.com/words?ml=${query}`)
        .then((res) => setResults(res.data))
        .catch((err) => console.error(err));
    } else {
      setResults([]);
    }
  }, [query]);

  return (
    <div style={{ padding: "20px", maxWidth: "500px", margin: "auto" }}>
      <input
        type="text"
        placeholder="Search for related words..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        style={{
          width: "100%",
          padding: "10px",
          fontSize: "16px",
          marginBottom: "10px",
        }}
      />
      <ul>
        {results.map((word, index) => (
          <li key={index}>{word.word}</li>
        ))}
      </ul>
    </div>
  );
};

export default SearchBarAPI;

I have executed the above example code and added the screenshot below.

Search Bar Component in React

Explanation:

  • I used axios to fetch data from the Datamuse API.
  • The results update dynamically as the user types.

This method is perfect when you need live suggestions from a backend or third-party API.

Method 3 – Debounced Search for Better Performance

If you’re hitting an API on every keystroke, it can overwhelm the server and slow down the app. That’s where debouncing comes in.

Here’s the complete code:

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

const SearchBarDebounced = () => {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);
  const [debouncedQuery, setDebouncedQuery] = useState(query);

  // Debounce logic
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedQuery(query);
    }, 500);

    return () => clearTimeout(timer);
  }, [query]);

  // Fetch API when debounced query changes
  useEffect(() => {
    if (debouncedQuery) {
      axios
        .get(`https://api.datamuse.com/words?ml=${debouncedQuery}`)
        .then((res) => setResults(res.data))
        .catch((err) => console.error(err));
    } else {
      setResults([]);
    }
  }, [debouncedQuery]);

  return (
    <div style={{ padding: "20px", maxWidth: "500px", margin: "auto" }}>
      <input
        type="text"
        placeholder="Search with debounce..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        style={{
          width: "100%",
          padding: "10px",
          fontSize: "16px",
          marginBottom: "10px",
        }}
      />
      <ul>
        {results.map((word, index) => (
          <li key={index}>{word.word}</li>
        ))}
      </ul>
    </div>
  );
};

export default SearchBarDebounced;

I have executed the above example code and added the screenshot below.

React Search Bar Component

Explanation:

  • I used a setTimeout to delay API calls until the user stops typing.
  • This improves performance and reduces unnecessary requests.

This method is widely used in production apps like Yelp or Amazon.

Method 4 – Reusable Search Component with Props

Often, I want a reusable search bar that I can drop into different parts of my app. Let’s create a flexible component that accepts props.

Here’s the full code:

import React, { useState } from "react";

const SearchBarReusable = ({ data, placeholder }) => {
  const [query, setQuery] = useState("");

  const filteredData = data.filter((item) =>
    item.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <div style={{ padding: "20px", maxWidth: "400px" }}>
      <input
        type="text"
        placeholder={placeholder}
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        style={{
          width: "100%",
          padding: "10px",
          fontSize: "16px",
          marginBottom: "10px",
        }}
      />
      <ul>
        {filteredData.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

// Example usage
const App = () => {
  const products = [
    "iPhone 15",
    "Samsung Galaxy S23",
    "MacBook Air",
    "Dell XPS",
    "iPad Pro",
    "Apple Watch",
    "Sony Headphones",
  ];

  return (
    <div>
      <h2>Product Search</h2>
      <SearchBarReusable data={products} placeholder="Search products..." />
    </div>
  );
};

export default App;

Explanation:

  • I passed data and a placeholder as props.
  • Now I can reuse this component for cities, products, or any dataset.

This method gives you flexibility and cleaner code.

Extra Tips for a Better Search Bar

  • Accessibility: Always add aria-label or placeholder text.
  • Styling: Use CSS or libraries like Tailwind for a polished look.
  • Highlight Matches: You can highlight matching text for better UX.
  • Keyboard Support: Allow navigation with arrow keys for advanced use cases.

Conclusion

Adding a search bar in React is one of those tasks that looks small but makes a huge difference in usability.

We explored four methods:

  1. Basic search with state and filter
  2. API-powered search with Axios
  3. Debounced search for performance
  4. Reusable search component with props

Each method has its place. For small apps, the first method is enough. For production apps, I often combine debouncing with API calls for the best performance.

Now you have all the tools to build a search bar that fits your project’s needs. Try these methods in your next React project, and you’ll see how much smoother the user experience becomes.

You may also like to read other React tutorials:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.