AniUI Academy
medium+200 XP

Build an autocomplete

Build a search box for a small, fixed list of fruit. Typing filters the list to items whose name starts with what has been typed so far, case-insensitively.

Picking a suggestion fills the input with it and closes the list.

Requirements

  • The fruit list is exactly: Apple, Apricot, Banana, Blueberry, Cherry, Coconut, Date, Grape.
  • There is exactly one `<input>` on the page.
  • Each suggestion renders as an `<li>` containing the fruit's full name as its text.
  • An empty input shows no suggestions.
  • Typing text that matches nothing shows no suggestions (not an error, not stale results).
  • Clicking a suggestion sets the input's value to that suggestion and closes the list — no `<li>` elements remain.

Your workspace

import { useState } from "react";

const FRUITS = ["Apple", "Apricot", "Banana", "Blueberry", "Cherry", "Coconut", "Date", "Grape"];

export default function App() {
  const [query, setQuery] = useState("");

  // TODO: compute the fruit whose name starts with `query`, case-insensitive.
  // An empty query should produce no suggestions.
  const suggestions = [];

  return (
    <div style={{ fontFamily: "sans-serif", padding: 16, maxWidth: 320 }}>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search fruit..."
        style={{ width: "100%", padding: 8, fontSize: 14, boxSizing: "border-box" }}
      />
      <ul style={{ listStyle: "none", padding: 0, marginTop: 4 }}>
        {suggestions.map((fruit) => (
          <li
            key={fruit}
            // TODO: clicking a suggestion should fill the input with it and
            // close the list.
            style={{ padding: 8, cursor: "pointer", borderBottom: "1px solid #eee" }}
          >
            {fruit}
          </li>
        ))}
      </ul>
    </div>
  );
}

Ready to check it?

5 tests run against your rendered component, right here in your browser. Sign in to claim the XP when you pass.

Stuck? The react course covers the ideas this problem is built on.