Combobox

A searchable single select built on the ARIA 1.2 combobox and listbox pattern. Type to filter (accent-insensitive, matching labels, descriptions and keywords, with the match highlighted), use the arrow keys, Enter to choose and Escape to close; clicking outside also closes it. Supports icons, descriptions and disabled options, an empty state, an optional clear button, a result count for screen readers and a hidden input for forms.

Forms & inputsComponentTailwind v4

Source

"use client";

import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { Check, ChevronsUpDown, X } from "lucide-react";
import { cn } from "@/lib/utils";

export interface ComboboxOption {
  value: string;
  label: string;
  description?: string;
  /** Extra words that should match the search, such as abbreviations or old names. */
  keywords?: string[];
  icon?: ReactNode;
  disabled?: boolean;
}

export interface ComboboxProps {
  options: ComboboxOption[];
  value?: string | null;
  defaultValue?: string | null;
  onValueChange?: (value: string | null) => void;
  label: ReactNode;
  hideLabel?: boolean;
  placeholder?: string;
  hint?: ReactNode;
  /** Shown when nothing matches. Receives the typed text. */
  emptyMessage?: (query: string) => ReactNode;
  disabled?: boolean;
  /** Shows a clear button while a value is selected. */
  clearable?: boolean;
  /** Submits the selected value with a form under this name. */
  name?: string;
  defaultOpen?: boolean;
  className?: string;
}

// Lowercases and strips accents one character at a time, so match positions line up with the original label.
function fold(text: string) {
  return Array.from(text, (char) => (char.normalize("NFD")[0] ?? char).toLowerCase()[0] ?? char).join("");
}

function rank(option: ComboboxOption, query: string) {
  const label = fold(option.label);
  if (label.startsWith(query)) return 0;
  if (label.split(/[\s\-_/().,]+/).some((word) => word.startsWith(query))) return 1;
  if (label.includes(query)) return 2;
  if ([option.description, ...(option.keywords ?? [])].some((text) => text && fold(text).includes(query))) return 3;
  return -1;
}

function filterOptions(options: ComboboxOption[], text: string) {
  const query = fold(text.trim());
  if (!query) return options;
  return options
    .map((option, index) => ({ option, index, score: rank(option, query) }))
    .filter((item) => item.score >= 0)
    .sort((a, b) => a.score - b.score || a.index - b.index)
    .map((item) => item.option);
}

function Highlight({ text, query }: { text: string; query: string }) {
  const at = query ? fold(text).indexOf(fold(query.trim())) : -1;
  if (at < 0 || !query.trim()) return <>{text}</>;
  const end = at + query.trim().length;
  return (
    <>
      {text.slice(0, at)}
      <span className="font-semibold text-foreground">{text.slice(at, end)}</span>
      {text.slice(end)}
    </>
  );
}

export function Combobox({
  options, value: controlled, defaultValue = null, onValueChange, label, hideLabel, placeholder = "Search…", hint,
  emptyMessage = (query) => <>No matches for “{query}”</>, disabled, clearable, name, defaultOpen = false, className,
}: ComboboxProps) {
  const id = useId();
  const ids = { label: `${id}-label`, input: `${id}-input`, list: `${id}-list`, hint: `${id}-hint` };
  const optionId = (index: number) => `${id}-option-${index}`;

  const [uncontrolled, setUncontrolled] = useState<string | null>(defaultValue);
  const value = controlled !== undefined ? controlled : uncontrolled;
  const selected = options.find((option) => option.value === value) ?? null;

  const [open, setOpen] = useState(defaultOpen);
  const [text, setText] = useState(selected?.label ?? "");
  const [filtering, setFiltering] = useState(false);
  const results = useMemo(() => (filtering ? filterOptions(options, text) : options), [filtering, options, text]);
  const firstEnabled = (list: ComboboxOption[]) => list.findIndex((option) => !option.disabled);
  const [active, setActive] = useState(() => {
    const index = options.findIndex((option) => option.value === value);
    return index >= 0 ? index : firstEnabled(options);
  });

  const rootRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLUListElement>(null);

  // Show the selected label whenever the user is not typing.
  useEffect(() => {
    if (!filtering) setText(selected?.label ?? "");
  }, [selected?.label, filtering]);

  function commit(next: string | null) {
    if (controlled === undefined) setUncontrolled(next);
    if (next !== value) onValueChange?.(next);
  }

  function openList(from: "selected" | "last" = "selected") {
    if (disabled) return;
    setFiltering(false);
    const selectedIndex = options.findIndex((option) => option.value === value && !option.disabled);
    const lastEnabled = options.map((option) => !option.disabled).lastIndexOf(true);
    setActive(from === "last" ? lastEnabled : selectedIndex >= 0 ? selectedIndex : firstEnabled(options));
    setOpen(true);
  }

  function close({ keepText = false } = {}) {
    setOpen(false);
    if (keepText) return;
    // An emptied field clears the value; anything else reverts to the current selection.
    if (clearable && filtering && !text.trim()) commit(null);
    setFiltering(false);
  }

  function choose(option: ComboboxOption | undefined) {
    if (!option || option.disabled) return;
    commit(option.value);
    setText(option.label);
    setFiltering(false);
    setOpen(false);
  }

  function move(step: 1 | -1) {
    if (!results.length) return;
    let next = active;
    for (let i = 0; i < results.length; i++) {
      next = (next + step + results.length) % results.length;
      if (!results[next].disabled) break;
    }
    setActive(next);
  }

  function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    switch (event.key) {
      case "ArrowDown":
        event.preventDefault();
        if (!open) openList();
        else if (!event.altKey) move(1);
        break;
      case "ArrowUp":
        event.preventDefault();
        if (!open) openList(event.altKey ? "selected" : "last");
        else if (event.altKey) close();
        else move(-1);
        break;
      case "Enter":
        if (!open) return;
        event.preventDefault();
        if (active >= 0 && results[active]) choose(results[active]);
        else close();
        break;
      case "Escape":
        if (!open) return;
        event.preventDefault();
        event.stopPropagation();
        close();
        break;
      case "Tab":
        if (open) close();
        break;
    }
  }

  // Clicking anywhere outside closes the list, including when it was opened without focus.
  useEffect(() => {
    if (!open) return;
    function handlePointer(event: PointerEvent) {
      if (!rootRef.current?.contains(event.target as Node)) close();
    }
    document.addEventListener("pointerdown", handlePointer);
    return () => document.removeEventListener("pointerdown", handlePointer);
  });

  // Keep the active option visible without scrolling the page.
  useEffect(() => {
    if (!open || active < 0) return;
    const list = listRef.current;
    const item = list?.querySelector<HTMLElement>(`[data-index="${active}"]`);
    if (!list || !item) return;
    if (item.offsetTop < list.scrollTop) list.scrollTop = item.offsetTop - 4;
    else if (item.offsetTop + item.offsetHeight > list.scrollTop + list.clientHeight)
      list.scrollTop = item.offsetTop + item.offsetHeight - list.clientHeight + 4;
  }, [active, open, results]);

  const activeOption = open && active >= 0 ? results[active] : undefined;
  const showEmpty = open && results.length === 0;

  return (
    <div ref={rootRef} className={cn("relative flex min-w-0 flex-col gap-1.5", className)}>
      <label id={ids.label} htmlFor={ids.input} className={cn("w-fit text-sm font-medium text-foreground", hideLabel && "sr-only")}>
        {label}
      </label>

      <div className="relative">
        <div
          data-disabled={disabled || undefined}
          className={cn(
            "flex h-9 w-full items-center gap-1 rounded-md border border-input bg-background pl-3 pr-1 text-sm shadow-xs shadow-black/[0.03]",
            "transition-[border-color,box-shadow] duration-150 dark:bg-input/20",
            "has-[input:focus-visible]:border-ring has-[input:focus-visible]:ring-[3px] has-[input:focus-visible]:ring-ring/40",
            "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-60",
          )}
        >
          {selected?.icon && !filtering && (
            <span aria-hidden="true" className="-ml-0.5 mr-1 flex shrink-0 items-center">{selected.icon}</span>
          )}
          <input
            ref={inputRef}
            id={ids.input}
            type="text"
            role="combobox"
            autoComplete="off"
            spellCheck={false}
            disabled={disabled}
            placeholder={placeholder}
            aria-expanded={open}
            aria-controls={ids.list}
            aria-autocomplete="list"
            aria-activedescendant={activeOption ? optionId(options.indexOf(activeOption)) : undefined}
            aria-describedby={hint ? ids.hint : undefined}
            value={text}
            onChange={(event) => {
              const next = event.target.value;
              setText(next);
              setFiltering(true);
              setActive(firstEnabled(filterOptions(options, next)));
              setOpen(true);
            }}
            onKeyDown={handleKeyDown}
            onClick={(event) => {
            if (open) return;
            openList();
            event.currentTarget.select();
          }}
            onBlur={(event) => {
              if (!rootRef.current?.contains(event.relatedTarget as Node)) close();
            }}
            className="h-full min-w-0 flex-1 bg-transparent text-foreground outline-hidden placeholder:text-muted-foreground/70 disabled:cursor-not-allowed"
          />
          {clearable && value && !disabled && (
            <button
              type="button"
              aria-label="Clear selection"
              onClick={() => {
                commit(null);
                setText("");
                setFiltering(false);
                inputRef.current?.focus();
              }}
              className="inline-flex size-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-hidden hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
            >
              <X aria-hidden="true" className="size-3.5" />
            </button>
          )}
          <button
            type="button"
            tabIndex={-1}
            disabled={disabled}
            aria-label={open ? "Hide options" : "Show options"}
            aria-controls={ids.list}
            aria-expanded={open}
            onMouseDown={(event) => event.preventDefault()}
            onClick={() => {
              if (open) close();
              else openList();
              inputRef.current?.focus();
            }}
            className="inline-flex size-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
          >
            <ChevronsUpDown aria-hidden="true" className="size-4" />
          </button>
        </div>

        <div
          hidden={!open}
          className={cn(
            "absolute inset-x-0 top-[calc(100%+6px)] z-50 overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground",
            "shadow-lg shadow-black/5 transition-[opacity,translate] duration-150 dark:shadow-black/40",
            "starting:opacity-0 motion-safe:starting:-translate-y-1",
          )}
        >
          <ul ref={listRef} id={ids.list} role="listbox" aria-labelledby={ids.label} className="relative max-h-64 overflow-y-auto p-1 empty:hidden">
            {results.map((option, index) => {
              const isSelected = option.value === value;
              const isActive = index === active;
              return (
                <li
                  key={option.value}
                  id={optionId(options.indexOf(option))}
                  role="option"
                  data-index={index}
                  aria-selected={isSelected}
                  aria-disabled={option.disabled || undefined}
                  data-active={isActive || undefined}
                  onMouseDown={(event) => event.preventDefault()}
                  onMouseMove={() => !option.disabled && active !== index && setActive(index)}
                  onClick={() => choose(option)}
                  className={cn(
                    "flex cursor-default select-none items-center gap-2.5 rounded-md px-2 py-1.5 text-sm text-popover-foreground",
                    "data-[active]:bg-accent data-[active]:text-accent-foreground",
                    "aria-disabled:pointer-events-none aria-disabled:opacity-45",
                  )}
                >
                  {option.icon && <span aria-hidden="true" className="flex shrink-0 items-center">{option.icon}</span>}
                  <span className="flex min-w-0 flex-1 flex-col">
                    <span className="truncate text-foreground/90">
                      <Highlight text={option.label} query={filtering ? text : ""} />
                    </span>
                    {option.description && <span className="truncate text-xs text-muted-foreground">{option.description}</span>}
                  </span>
                  <Check aria-hidden="true" className={cn("size-4 shrink-0", isSelected ? "opacity-100" : "opacity-0")} />
                </li>
              );
            })}
          </ul>
          {showEmpty && <p className="px-3 py-6 text-center text-sm text-muted-foreground">{emptyMessage(text.trim())}</p>}
        </div>
      </div>

      {hint && <p id={ids.hint} className="text-[13px] leading-5 text-muted-foreground">{hint}</p>}

      <span role="status" aria-live="polite" className="sr-only">
        {open && filtering ? `${results.length} ${results.length === 1 ? "result" : "results"}` : ""}
      </span>
      {name && <input type="hidden" name={name} value={value ?? ""} />}
    </div>
  );
}