React: A filterable list

The smallest example of the process: one piece of state, one derived list.

What to build

A list of names with a search box that filters it.

Requirements

  • Keep NAMES. A controlled input with the id filter filters the names to those containing the text (ignoring case), shown as li items of a ul with the id names.
  • When nothing matches, show a p with the id empty: No matches, and no list items.

Constraints

Only the text is state; the filtered list is computed.

Example

Typing "ra" shows Rahim, Grace and Farah.

Why it works

The text is the only thing that changes and cannot be computed, so it is the only state; the list is worked out from it on every render.

Hints

Hint 1

The search text is the only state; the filtered list is computed during render.

Hint 2

Show "No matches" when the filtered list is empty.

Solution

Show one correct solution (try it yourself first)
import { useState } from "react";

const NAMES = ["Rahim", "Ada", "Rina", "Grace", "Farah", "Alan"];

export default function App() {
  const [text, setText] = useState("");
  const shown = NAMES.filter((n) => n.toLowerCase().includes(text.toLowerCase()));
  return (
    <div>
      <input id="filter" value={text} onChange={(e) => setText(e.target.value)} />
      <ul id="names">
        {shown.map((n) => (
          <li key={n}>{n}</li>
        ))}
      </ul>
      {shown.length === 0 && <p id="empty">No matches</p>}
    </div>
  );
}

Lesson: Thinking in React →