Katkat

Build a React Typeahead with Async Suggestions and Keyboard Navigation

xAIFrontend Engineer · Onsite

Last updated

A frontend coding question: build a React typeahead, a search input whose dropdown shows suggestions fetched asynchronously as the user types. The dropdown must support arrow keys, Enter, Escape and mouse selection, so it tests hooks, handling of out-of-order responses, accessibility and UI state.

Build a typeahead component in React: a search input that shows a dropdown of suggestions while the user types. Suggestions come from an asynchronous data source, and the dropdown must be fully usable from the keyboard. This is one of two questions in a 45-minute frontend coding round.

Assume the data source is given as a function that resolves to the suggestions for a query and stops its work when the abort signal fires:

type FetchSuggestions = (query: string, signal: AbortSignal) => Promise<string[]>;

Requirements:

  • While the user types, show the suggestions for the current input text in a dropdown under the input.
  • The Up and Down arrow keys move a highlight through the suggestions, Enter selects the highlighted suggestion, and Escape closes the dropdown.
  • Clicking a suggestion selects it.
  • Selecting a suggestion puts its text into the input, closes the dropdown, and reports the selection to the parent component.

Constraints and Clarifications

  • Use React function components and hooks.
  • No third-party autocomplete or combobox component; the behavior is the point of the exercise.

Clarifying Questions

  • Should requests be debounced, and is there a minimum number of characters before the first request?
  • May results be cached per query?
  • What should Enter do when no suggestion is highlighted: submit the raw text, or nothing?
  • Should arrow navigation wrap from the last suggestion to the first?
  • What should the dropdown show while loading, when there are no matches, and when the request fails?
  • Is screen-reader support in scope?

Hints

Hint 1

Fast typing, slow network: Imagine typing four characters quickly while each request takes a different amount of time to come back. Decide which response the dropdown is allowed to show.

Hint 2

The state the keyboard needs: List the pieces of state your key handler reads and writes, and decide which user actions should reset each of them.

Follow-up questions

  • How would you highlight the part of each suggestion that matches the query, safely?
  • The data source can return thousands of suggestions. What changes?
  • How would you make the component reusable for suggestion objects rather than strings, with custom rendering of each row?
  • Users type in languages that rely on an input method editor. What can break in your key handling, and how do you fix it?