Frontend fundamentals

How a simple live search in React works, from filtering as you type to the small touches that make it accessible.How a simple live search in React works.

Building Blocks

Live
Search

One input, one list.
A little search to build on.

· TODO min readComponents, React, Accessibility

What is a live search?

A live search updates the results as you type, without waiting for you to hit submit. Try the super simple, interactive example below, then we’ll build it piece by piece so you can see what’s happening behind the UI. Understanding these fundamentals is a great starting point for fancier features, like highlighting the matching text and keyboard-friendly suggestions.

12 colors

  • turquoise
  • gold
  • hotpink
  • dodgerblue
  • deeppink
  • springgreen
  • deepskyblue
  • orangered
  • darkorange
  • blueviolet
  • chartreuse
  • magenta

Try typing “blue” or “orange”.

The anatomy

At its simplest, live search is an input and a list that updates as you type. A label, a results count, and a helpful empty state make it clear what to search, how many matches remain, and when to try something else.

2 colors

  • deeppink
  • hotpink
A live search with “pink” typed in, showing two matching colors. Its parts are described in the list below.

Hover over a part below, or tab to it, to highlight it in the example.Click a part below to highlight it in the example.

Build it in React

Let’s start with the bare bones: a list, an input, and a filter. We’ll build it up one small piece at a time, then add the accessibility touches once the search is working.

Start with the data

Every search needs something to search through. In a real app, this might be products, contacts, or notes, probably fetched from somewhere and stored as objects with an id, a name, and more. Here, we’ll keep it simple with an array of strings: a few of CSS’s built-in named colors.

const COLORS = [
  "turquoise",
  "blueviolet",
  "hotpink",
  "darkorange",
  "deepskyblue",
  "deeppink",
  "dodgerblue",
  "chartreuse",
  "gold",
  "orangered",
  "magenta",
  "springgreen",
];

Keep the query in state

The only thing React needs to remember is what you’ve typed into the search field. That goes in state: a value React remembers between renders, where changing it redraws the component. The search term starts as an empty string.

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

<input
  type="search"
  value={searchTerm}
  onChange={(e) => setSearchTerm(e.target.value)}
/>

This is a controlled input: value tells the input what to show, and onChange updates state with every keystroke. e.target.value is whatever’s in the input right now.

Each keystroke updates searchTerm and re-renders the component, so the list can update right away. That re-render is what makes the search feel live.

New to useState or controlled inputs? I keep quick refreshers in my Field Notes: useState and controlled inputs.

Work out the results

Next we need to filter the color list using what’s been typed into the input. We don’t need to store the results in state because we can work them out from searchTerm on every render with filter().

const filteredColors = COLORS.filter((color) =>
  color.includes(searchTerm)
);

filter() goes through the list and keeps only the colors where the check returns true. Here, the check is includes(), which asks: does this color name contain what was typed?

New to these? My Field Notes have quick refreshers on map / filter / find and includes().

Match loosely

Right now, “Blue” finds nothing. Neither does “ blue” because of the sneaky space in front. That’s because includes() matches characters exactly: a capital “B” isn’t the same as a lowercase “b”, and no color name has a space in it.

As someone whose typing could use a little grace, let’s return the favor. Trimming the spaces from either end and converting the query to lowercase makes the search more forgiving.

My color names are already lowercase, so I only need to tidy up the query. With mixed-case data, like product names, you’d lowercase both sides: name.toLowerCase().includes(query).

const query = searchTerm.trim().toLowerCase();

const filteredColors = COLORS.filter((color) =>
  color.includes(query)
);

Show the results

Last step! We’ve narrowed down the list with filter(), and now map() turns those matches into list items. Each item needs a key so React can keep track of it as the list shrinks and grows. Our color names are unique, so they make perfect keys. For something like products or contacts, we’d usually use each item’s ID.

<ul>
  {filteredColors.map((color) => (
    <li key={color}>
      <span className="swatch" style={{ background: color }} />
      {color}
    </li>
  ))}
</ul>

I also added little color swatches to jazz things up. They’re a fun freebie: each name is already a valid CSS color, so it can paint its own little square.

Put it together

Here’s the whole thing. It works! You can type, and the list filters as you go. But it’s not quite finished: there’s no label, nothing tells screen reader users that the results changed, and searching for “blurple” leaves an awkward empty space. Let’s fix those next.

import { useState } from "react";

export default function ColorSearch() {
  const [searchTerm, setSearchTerm] = useState("");

  const query = searchTerm.trim().toLowerCase();
  const filteredColors = COLORS.filter((color) => color.includes(query));

  return (
    <>
      <input
        type="search"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <ul>
        {filteredColors.map((color) => (
          <li key={color}>
            <span className="swatch" style={{ background: color }} />
            {color}
          </li>
        ))}
      </ul>
    </>
  );
}

Make it accessible

Our search works! Let’s fill in a few gaps to make sure it’s more accessible: give the input a label, announce the results, and show a helpful message when nothing matches. None of these take much code, but each makes it easier to understand what to search, what changed, and what to try next.

Give it a label

Let’s tell people what they’re searching. A proper <label> stays put while you type, and it gives the input a name that screen readers can announce. A placeholder can offer a hint, but it disappears as soon as you start typing, so it can’t do the label’s job.

The label and input need to be connected, so the browser knows they belong together. The label’s htmlFor points to the input’s id:

<label htmlFor="color-search">Search colors</label>
<input id="color-search" type="search" />

Now screen readers announce “Search colors” when the input is focused, and clicking the label focuses the input too. htmlFor is React’s name for HTML’s for attribute, since for already means something in JavaScript.

One catch: an id has to be unique on the page. If this search ever shows up twice, both inputs would get color-search, and each label could end up pointing at the wrong one. React’s useId() fixes that by making a unique ID for every copy of the component:

const searchId = useId();

<label htmlFor={searchId}>Search colors</label>
<input
  id={searchId}
  type="search"
  value={searchTerm}
  onChange={(e) => setSearchTerm(e.target.value)}
/>

Just remember to import useId from "react", like useState. More on it in my useId field note.

A visible label is usually best, but if you want to tuck it away, an sr-only (screen reader only) class hides it visually while keeping it available to screen readers. That’s what my demo at the top does; the anatomy example leaves it visible.

Use type="search"

You may have noticed type="search" in the input from the start. It’s a tiny change that comes with a few freebies: some browsers add a clear button, Escape clears the field, and phones show a search key on the keyboard. Screen readers also announce it as a search field.

Announce the results

When you type, the list shrinks right away. That’s obvious if you can see it, but a screen reader user hears nothing. A live region gives them a little heads-up: as the number of matches changes, screen readers can announce the updated count.

const count = filteredColors.length;

<p aria-live="polite">
  {count} {count === 1 ? "color" : "colors"}
</p>

polite tells the screen reader to wait its turn. As you type, it’s already reading back each letter, so it finishes that first and then announces the count. The count helps everyone else too, as a quick “how many are left?”

Say when nothing matches

Search for “blurple” and the list just disappears. Is it broken? Still loading? An empty state answers that, and nudges people to try something else.

{count > 0 ? (
  <ul>{/* the list from before */}</ul>
) : (
  <p>No colors called “{searchTerm}”… yet.</p>
)}

Screen reader users already hear “0 colors” from the live region, so this one is mostly for sighted users. Using their search term in the message shows the search worked, there just wasn’t a match.

Put it all together

Here’s the finished search: a label, a live count, and an empty state, on top of the search we built before. It’s the same one as the demo at the top, minus my styling.

import { useId, useState } from "react";

export default function ColorSearch() {
  const [searchTerm, setSearchTerm] = useState("");
  const searchId = useId();

  const query = searchTerm.trim().toLowerCase();
  const filteredColors = COLORS.filter((color) => color.includes(query));
  const count = filteredColors.length;

  return (
    <>
      <label htmlFor={searchId}>Search colors</label>
      <input
        id={searchId}
        type="search"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <p aria-live="polite">
        {count} {count === 1 ? "color" : "colors"}
      </p>
      {count > 0 ? (
        <ul>
          {filteredColors.map((color) => (
            <li key={color}>
              <span className="swatch" style={{ background: color }} />
              {color}
            </li>
          ))}
        </ul>
      ) : (
        <p>No colors called “{searchTerm}”… yet.</p>
      )}
    </>
  );
}

Test it

Let’s check how our search behaves beyond the mouse. The exact wording you hear will vary by browser and screen reader, but the gist should match.

With a keyboard

  1. Press Tab to move into the search.
  2. Type a search. The results should update while the cursor stays put.
  3. Press Esc to clear it, and the whole list comes back.

With a screen reader

On a Mac, turn on VoiceOver with ⌘ + F5 (you may also need Fn).

  1. Tab to the search. You should hear its label, “Search colors”.
  2. Type blue. Listen for the updated count.
  3. Try blurple. You should hear zero results, and see the empty message on screen.

Keep going

One input, one bit of state, and a list that follows along. Add a label, a results count, and a helpful empty message, and we’ve got a little search to build on.

A few ideas to build on next (some of these are coming in a follow-up post):

  • Highlight the match. Wrap the matching part of each name in a <mark> so it’s easy to spot.
  • Search more fields. Try a list of products and match against names, categories, or tags.
  • Keyboard-friendly suggestions. A dropdown of suggestions under the input, with arrow keys to move through them. That’s a combobox, and it’s a bigger build.

Want to go deeper? These are the references I lean on:

Check out the Forms section of my Sedge design system.

More Building Blocks are on the way. 🌱

Back to top