FrontendInterviews.dev

Loading problem…

43. Autocomplete

Easy•

Build an Autocomplete component in React that filters a list of options as the user types and allows selection via keyboard or mouse.

Requirements

1. Input Field

  • Text input for user typing
  • Filter options based on input value
  • Case-insensitive matching

2. Dropdown List

  • Show filtered options below input
  • Highlight matching text in options
  • Show/hide dropdown based on input focus and matches

3. Selection

  • Click option to select
  • Keyboard navigation (Arrow Up/Down, Enter)
  • Update input value on selection
  • Close dropdown after selection

4. Data Structure

interface AutocompleteProps {
  options: string[];
  onSelect?: (value: string) => void;
  placeholder?: string;
}

Example Usage

const options = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

<Autocomplete 
  options={options}
  onSelect={(value) => console.log('Selected:', value)}
  placeholder="Search fruits..."
/>

Constraints

  • Handle keyboard navigation (Arrow keys, Enter, Escape)
  • Filter options case-insensitively
  • Highlight matching text in options
  • Close dropdown when clicking outside