KatInterview

Searchable Dropdown Input with Live Async Suggestions in React

Data Structure DesignModel answer

Last updated

Implement a React search box whose dropdown fills with suggestions from an abortable async source and works fully by keyboard and mouse, without ever showing outdated results.

Task

Implement a reusable search-as-you-type component in React. As the user enters text, a dropdown below the input lists matching suggestions retrieved from an asynchronous source. The list must be fully operable with the keyboard as well as the mouse.

The data source is supplied as a function. It resolves to the suggestions for a given query and should cancel its work when the abort signal fires:

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

Required behavior

  • While the user types, show the suggestions that correspond to the current text in a dropdown under the input.
  • Arrow Up / Arrow Down move a highlight through the listed suggestions.
  • Enter chooses the highlighted suggestion.
  • Escape closes the dropdown.
  • Clicking a suggestion chooses it.
  • Choosing a suggestion must: write its text into the input, close the dropdown, and notify the parent component (for example through an onSelect callback).

Constraints

  • Use React function components and hooks only.
  • Do not use a third-party autocomplete or combobox library. The behavior itself is what is being evaluated.

Decisions to state out loud

Because the spec leaves several things open, explain which choice you make and why:

  • Is the request debounced, and is there a minimum query length?
  • Are results cached per query?
  • What does Enter do when nothing is highlighted?
  • Does arrow navigation wrap around at either end?
  • What does the dropdown display while loading, when nothing matches, and when the request fails?
  • Is screen-reader support included?

Provide the component code and walk through your design, including how you would test it.

Hints

Hint 1

Keep a small state model: the input text, the suggestion list, a status (idle, loading, error), an open flag and a highlighted index. Reset the highlight whenever the list changes.

Hint 2

Fetch inside an effect keyed on the (debounced) query. Create an AbortController in the effect and abort it in the cleanup, and also ignore any result that arrives after cleanup has run. That guarantees an old response can never overwrite a newer one.

Hint 3

Clicking an option blurs the input before the click fires, which can close the list too early. Handle onMouseDown on options (with preventDefault), or delay closing on blur.

Hint 4

For accessibility, use role=combobox on the input with aria-expanded, aria-controls and aria-activedescendant, a role=listbox container, and role=option with aria-selected on each item.