Skip to the page

Search, lists and data · mid

Autocomplete / combobox component

An autocomplete builds on debounced search with an activeIndex for keyboard navigation, the ARIA combobox roles with focus kept on the input, safe highlighting of the match, closing on Escape and outside click, and a generic API so the same component serves many lists.

The notes

What you must know

  • State: query, results, status, isOpen, activeIndex (−1 = none).
  • Keyboard: Down/Up move activeIndex (wrap or clamp — say which), Enter selects the active option, Escape closes, Tab closes; mouse hover sets activeIndex.
  • ARIA (APG combobox): input role='combobox', aria-expanded, aria-controls='listbox-id', aria-activedescendant='option-id', aria-autocomplete='list'; ul role='listbox'; li role='option' with id and aria-selected. DOM focus stays on the input.
  • Scroll the active option into view: element.scrollIntoView({ block: 'nearest' }).
  • Click on an option fires after the input's blur: use onMouseDown/pointerdown with preventDefault on options, or close on outside pointerdown instead of on blur.
  • Highlight the match by splitting the text into parts and wrapping matches in <mark>; never build HTML strings from the query.
  • Generic API (Razorpay/JioHotstar 'reusable searchable dropdown'): options or an async loadOptions, getOptionLabel, renderOption, onSelect, placeholder, multi-select mode with chips (Backspace on an empty input removes the last chip).
  • Large lists: cap results or virtualise the listbox; IME composition: don't search mid-composition.

The red pen

Common traps: mistake → fix

  • Mistake: Move real DOM focus into the list

    Fix: the user can't keep typing; use aria-activedescendant.

  • Mistake: Close the list on input blur

    Fix: the option click never registers.

  • Mistake: innerHTML for highlighting

    Fix: XSS and broken output for '.' or '('.

  • Mistake: Forget Escape and outside click

    Fix: the popup gets stuck open.

Easy to hard

Questions interviewers ask, easy to hard

  1. Build an autocomplete over this API.
  2. Add keyboard navigation and selection.
  3. Make it accessible.
  4. Make it reusable for any list, then multi-select with chips.

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview