Typeahead With Keyboard Navigation

MediumAsyncKeyboardAccessibilityReact35 mins

by Pratik Rai

Read the full write-up

A city search that queries as you type, once you have entered at least three characters.

The search function has deliberately variable latency, so responses come back out of order — making sure a slow earlier request never overwrites a newer one is the point of the exercise.

Requirements

  1. Search only once the query is at least MIN_CHARS long; below that, clear the results.

  2. Debounce so a request is not made for every keystroke.

  3. A response for a query that is no longer current must never be shown — abort it.

  4. Arrow Up and Arrow Down move through results, Enter selects, Escape closes.

  5. Selecting fills the input and closes the list without immediately searching again.

  6. The input is a role="combobox" with aria-expanded and aria-activedescendant; results are a role="listbox" of options.

Notes

  • searchCities accepts an AbortSignal and rejects with an AbortError when cancelled.

  • Latency is randomised between roughly 200 and 800ms, so out-of-order responses happen on their own — type quickly and watch.

Hints

Loading editor…