Skip to main content

Lesson 6 of 8

Search, Autocomplete & Combobox

Search with autocomplete is one of the most common and nuanced UI patterns: debounce to limit requests, AbortController to cancel stale requests, keyboard navigation for accessibility, and the combobox ARIA pattern for screen readers.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Accessible Autocomplete Search

Accessible Autocomplete Search
import { useState, useEffect, useRef, useCallback, useId } from 'react';

function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return debounced;
}

interface SearchResult { id: string; name: string; category: string; }

function Autocomplete({ onSelect, placeholder = 'Search...' }: {
  onSelect: (result: SearchResult) => void;
  placeholder?: string;
}) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [activeIndex, setActiveIndex] = useState(-1);
  const [isLoading, setIsLoading] = useState(false);
  const debouncedQuery = useDebounce(query, 300);
  const inputRef = useRef<HTMLInputElement>(null);
  const listboxId = useId();

  // Fetch with cancellation
  useEffect(() => {
    if (!debouncedQuery.trim()) { setResults([]); setIsOpen(false); return; }
    const controller = new AbortController();
    setIsLoading(true);

    searchApi(debouncedQuery, controller.signal)
      .then(data => { setResults(data); setIsOpen(data.length > 0); setActiveIndex(-1); })
      .catch(err => { if (err.name !== 'AbortError') setResults([]); })
      .finally(() => setIsLoading(false));

    return () => controller.abort();
  }, [debouncedQuery]);

  const handleSelect = useCallback((result: SearchResult) => {
    setQuery(result.name);
    setIsOpen(false);
    setActiveIndex(-1);
    onSelect(result);
  }, [onSelect]);

  function handleKeyDown(e: React.KeyboardEvent) {
    if (!isOpen) return;
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setActiveIndex(i => Math.min(i + 1, results.length - 1));
        break;
      case 'ArrowUp':
        e.preventDefault();
        setActiveIndex(i => Math.max(i - 1, -1));
        break;
      case 'Enter':
        e.preventDefault();
        if (activeIndex >= 0) handleSelect(results[activeIndex]);
        break;
      case 'Escape':
        setIsOpen(false);
        setActiveIndex(-1);
        inputRef.current?.focus();
        break;
    }
  }

  return (
    <div style={{ position: 'relative' }} onKeyDown={handleKeyDown}>
      {/* Combobox ARIA pattern */}
      <input
        ref={inputRef}
        role="combobox"
        aria-expanded={isOpen}
        aria-haspopup="listbox"
        aria-controls={listboxId}
        aria-activedescendant={activeIndex >= 0 ? `option-${results[activeIndex].id}` : undefined}
        aria-label="Search"
        value={query}
        onChange={e => { setQuery(e.target.value); if (!e.target.value) setIsOpen(false); }}
        onFocus={() => { if (results.length > 0) setIsOpen(true); }}
        onBlur={() => setTimeout(() => setIsOpen(false), 150)} // delay to allow click on option
        placeholder={placeholder}
        style={{ width: '100%', padding: '10px 16px', borderRadius: 8, border: '1px solid #334155', background: '#1e293b', color: 'white', fontSize: 14 }}
      />
      {isLoading && <span aria-live="polite" aria-label="Loading results" style={{ position: 'absolute', right: 12, top: 12, color: '#64748b', fontSize: 13 }}>โŸณ</span>}

      {isOpen && (
        <ul
          id={listboxId}
          role="listbox"
          aria-label="Search results"
          style={{ position: 'absolute', top: '100%', left: 0, right: 0, background: '#1e293b', border: '1px solid #334155', borderRadius: 8, marginTop: 4, listStyle: 'none', padding: 4, zIndex: 50, maxHeight: 240, overflowY: 'auto' }}
        >
          {results.map((result, index) => (
            <li
              key={result.id}
              id={`option-${result.id}`}
              role="option"
              aria-selected={index === activeIndex}
              onMouseDown={() => handleSelect(result)}
              onMouseEnter={() => setActiveIndex(index)}
              style={{
                padding: '10px 12px',
                borderRadius: 6,
                cursor: 'pointer',
                background: index === activeIndex ? '#334155' : 'transparent',
              }}
            >
              <span style={{ fontWeight: 600, fontSize: 14 }}>{result.name}</span>
              <span style={{ fontSize: 12, color: '#64748b', marginLeft: 8 }}>{result.category}</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

Tip

Tip

Practice Search Autocomplete Combobox in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for Search, Autocomplete & Combobox

Practice Task

Note

Practice Task - (1) Write a working example of Search Autocomplete Combobox from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Search Autocomplete Combobox is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done