How to Create a Search Bar with React: A Step-by-Step Guide

How to Create a Search Bar with React: A Step-by-Step Guide

A quick guide to make an efficient search bar

Step 1: Setting Up the Component Structure

We’ll create three components:

  1. Search: This component will handle the search input.

  2. List: This component will display the filtered list of items based on the search query.

  3. SearchPage: This is the main component that ties everything together.

Let’s start by setting up these components in a single file for simplicity.

// Search.jsx

'use client';
import React, { useState } from 'react';

export default function SearchPage() {
    return <div>hello search page</div>
}

Step 2: Creating the Search Component

The Search component is a simple input field that will take user input and pass it to the parent component (SearchPage) using a state update function.

// Search.jsx

'use client';
import React, { useState } from 'react';

function Search({ search, setSearch }) {
  return (
    <input
      type="text"
      value={search}
      onChange={(e) => setSearch(e.target.value)}
      className="px-2 py-1 border rounded"
    />
  );
}

export default function SearchPage() {
    const [search, setSearch] = useState('');
    return <div>
        <Search {...{ search, setSearch }} />
    </div>
}

Step 3: Creating the List Component

The List component receives an array of items as a prop and displays them. If the array is empty, it shows a "No result" message.

// Search.jsx
...
function List({ items }) {
  if (items.length === 0) return <div>No result.</div>;
  return (
    <ul className="flex flex-col gap-2">
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}
...

Step 4: Creating the Main Component

The SearchPage component ties everything together. It holds the state for the search query and the list of items.

'use client';
import React, { useState } from 'react';

function Search({ search, setSearch }) {
  return (
    <input
      type="text"
      value={search}
      onChange={(e) => setSearch(e.target.value)}
      className="px-2 py-1 border rounded"
    />
  );
}

function List({ items }) {
  if (items.length === 0) return <div>No result.</div>;
  return (
    <ul className="flex flex-col gap-2">
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}

export default function SearchPage() {
  const [search, setSearch] = useState('');
  const [items, setItems] = useState([
    "Understanding React useEffect",
    "JavaScript ES6 Features",
    "Introduction to TypeScript",
    "CSS Grid Layout",
    "Node.js Crash Course",
  ]);

  return (
    <div>
      <Search {...{ search, setSearch }} />
      <List
        {...{
          items: search
            ? items.filter((item) =>
                item.toLowerCase().includes(search.toLowerCase())
              )
            : items,
        }}
      />
    </div>
  );
}

Explanation:

  • State Management: The SearchPage component manages two pieces of state:

    • search: Holds the current search query.

    • items: Contains the list of items to be filtered.

  • Filtering Logic: The List component receives a filtered list of items based on the search query. The filter method checks if each item includes the search query, ignoring case sensitivity.

Congratulations! You’ve successfully created a search bar in React that filters a list of items based on user input.

Codewithguillaume