HeadlessCombobox

React
@pdanpdan/headless-combobox-react

A render-prop component. Pass value and onChange for a controlled combobox, or omit value and use defaultValue for an uncontrolled one.

Install

pnpm add @pdanpdan/headless-combobox-react

Binding

The component and useHeadlessCombobox share the same options and return the same scope object.

<HeadlessCombobox
  options={options}
  value={value}
  onChange={setValue}
>
  {(scope) => (
    <div ref={scope.setContainerRef}>
      <button ref={scope.setTriggerRef} {...toReactProps(scope.triggerProps)}>
        {value ?? 'Select…'}
      </button>
      {scope.isOpen && (
        <ul {...toReactProps(scope.listboxProps)}>
          {scope.filteredOptions.map((option, index) => (
            <li
              key={option}
              {...toReactProps(scope.getOptionProps(option, index))}
            >
              {option}
            </li>
          ))}
        </ul>
      )}
    </div>
  )}
</HeadlessCombobox>

Structure

Each part of the markup receives a piece of the scope. Bind only the parts you render. Spread a prop bag with toReactProps.

Trigger + popup: a button opens a list below it. Most examples use this layout.

HeadlessCombobox (scope)
└─ div ref={scope.setContainerRef}                   widget boundary (optional)
   ├─ button ref={scope.setTriggerRef}                the trigger
   │  │        {...toReactProps(scope.triggerProps)}
   │  └─ selected label
   ├─ div ref={scope.setDropdownRef}                  the popup
   │  │      style={scope.popupStyle} popover="manual"
   │  └─ ul {...toReactProps(scope.listboxProps)}
   │     └─ scope.filteredOptions.map((option, i) => (
   │        <li {...toReactProps(scope.getOptionProps(option, i))}
   │            ref={(el) => scope.setOptionRef(option, el)} />))
   └─ input ref={scope.setInputRef}                    search input (optional)
           {...toReactProps(scope.inputProps)}

Typeahead: the text input itself is the combobox. Typing reopens the popup and filters.

HeadlessCombobox (scope)
└─ div ref={scope.setContainerRef}                   widget boundary (optional)
   ├─ input ref={(el) => {
   │         scope.setTriggerRef(el);
   │         scope.setInputRef(el);
   │       }}
   │       {...toReactProps(scope.comboboxInputProps)}  the combobox input
   └─ div ref={scope.setDropdownRef}                  the popup
      │      style={scope.popupStyle} popover="manual"
      └─ ul {...toReactProps(scope.listboxProps)}
         └─ scope.filteredOptions.map((option, i) => (
            <li {...toReactProps(scope.getOptionProps(option, i))}
                ref={(el) => scope.setOptionRef(option, el)} />))

Markup → scope

NameTypeDescription
wrapper elementsetContainerRefWidget boundary for click-outside and focus. Optional, recommended.
trigger buttontriggerProps, setTriggerRefrole="combobox". Toggles the popup and handles keyboard navigation.
typeahead inputcomboboxInputProps, setTriggerRef, setInputRefThe input is the combobox: typing reopens and filters.
search inputinputProps, setInputRefrole="searchbox". Filters while the popup stays open.
popup elementpopupStyle, setDropdownRefPositioning; add popover="manual" to use the native Popover API.
list elementlistboxProps, setListRefrole="listbox". The options container.
each option elementgetOptionProps(option, index), setOptionRef(option, el)Option semantics and select/highlight handlers.

Ref setters are optional. setOptionRef enables alignSelected and scroll-into-view; setContainerRef extends the click-outside boundary, for example to chips outside the field.

For CSS anchor positioning and the popover entry animation, see Styling.

Examples

The preview runs the Vue implementation. The code tab shows the same example for React.

The preview uses the native Popover API. Keyboard and hover share the same highlight, and the selected option is marked with a check.

Text options · single · no filter

A list of plain string options, single selection, no search input.

Framework (single, no filter)

Text options · single · internal state

An initial value seeds the internal selection; without a change handler the component keeps it internally.

Framework (single, no v-model)

Text options · single · select on tab

Press Tab with an option highlighted: it is selected and the popup closes (selectOnTab).

Framework (single, select on tab)

Object options · single · with filter

Object options with a searchable input.

Assign user (single, with filter)

Object options · single · separate value

Options carry a label and a value; the model holds the value only.

Framework id (single, separate value)

Text options · multiple · with filter

Multiple selection capped with max; selecting toggles, dropdown stays open.

Frameworks (multiple, max 3)

Text options · multiple · removable chips

Selected items as removable chips. The remove buttons live outside the combobox trigger, so the trigger stays a single focusable control.

Frameworks (multiple, max 3)
Vue Svelte

Text options · multiple · custom options

Each option renders its own checkbox for the selection state; the trigger shows the selected items as chips.

Frameworks (multiple, custom options)

Object options · multiple · validated

Multiple selection with required + min/max validation and a rendered message.

Reviewers (multiple, 2 to 4 required)

Select at least 2 options.

Select alignment

No search input; the dropdown aligns so the selected option overlays the trigger.

Assign user

Typeahead (editable combobox)

Canonical APG editable pattern: the text input itself is the combobox (role=combobox); type to filter.

Language (typeahead, editable)

Typeahead · chips inside the field

GitHub-style topic input: chips and the text input share one bordered field. The field is a plain container, so each chip can carry a remove button without nesting controls.

Topics (typeahead, removable chips in the field)
TypeScript

Composable · single · typeahead

The same behavior without the component. useHeadlessCombobox exposes the state, ARIA bags, and actions; wire the markup with plain refs.

Language (composable, typeahead)

Composable · programmatic control

open, close, select, and clear are plain functions, so the buttons outside the widget can call them. clickOutsideFilter keeps the popup open while the panel is used.

Drive it from anywhere:

Selected: none · popup closed

Member (composable, programmatic)

useHeadlessCombobox

HeadlessCombobox is a render-prop wrapper around useHeadlessCombobox. Use the hook when the markup cannot sit inside the component.

Pass value for controlled use, or omit it and use defaultValue. onChange receives every selection change. The hook returns the same scope object as the render prop.

Spread ARIA bags with toReactProps; actions are plain functions on the scope.

import { useState } from 'react';
import { toReactProps, useHeadlessCombobox } from '@pdanpdan/headless-combobox-react';

interface User {
  id: number;
  name: string;
}

const users: User[] = [
  { id: 1, name: 'Wade Cooper' },
  { id: 2, name: 'Arlene Mccoy' },
];

export function Example() {
  const [ value, setValue ] = useState<User | null>(null);
  const scope = useHeadlessCombobox({
    options: users,
    value,
    optionLabel: (user) => user.name,
    onChange: (next) => setValue(next as User | null),
  });

  return (
    <div ref={scope.setContainerRef}>
      <input
        ref={(el) => {
          scope.setTriggerRef(el);
          scope.setInputRef(el);
        }}
        {...toReactProps(scope.comboboxInputProps)}
        aria-label="Search users"
      />
      {scope.isOpen && (
        <ul {...toReactProps(scope.listboxProps)}>
          {scope.filteredOptions.map((user, index) => (
            <li
              key={user.id}
              ref={(el) => scope.setOptionRef(user, el)}
              {...toReactProps(scope.getOptionProps(user, index))}
            >
              <button type="button" onClick={() => scope.select(user)}>
                {user.name}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

The Composable · single · typeahead and Composable · programmatic control examples above show full usage.

API

Props

These are component and hook options. The value binding is listed first.

NameTypeDefaultDescription
valueV | V[] | nulln/aControlled value. Omit it for uncontrolled usage.
defaultValueV | V[] | nullnullInitial value when value is omitted.
onChange(value: V | V[] | null) => voidn/aCalled for every selection change.
optionsO[]n/aList of options.
multiplebooleanfalseEnable multiple selection.
minLengthnumbern/aMultiple: minimum number of selected options (validation).
maxLengthnumbern/aMultiple: maximum selected. Blocks adding beyond it.
requiredbooleanfalseRequire a selection (single: a value; multiple: at least one).
disabledbooleanfalseDisable the control: not focusable, cannot open or change.
readonlybooleanfalseRead-only: focusable, shows the value, but cannot open or change.
closeOnSelectboolean | null!multipleClose the dropdown after selecting.
closeOnClickOutsidebooleantrueClose when clicking outside the widget boundary.
clickOutsideFilter(target: EventTarget | null) => booleann/aReturn false to keep the dropdown open for an outside target.
selectOnTabbooleanfalseOn Tab, when focus leaves the widget: select the highlighted option and close.
optionValue(option: O) => Voption itselfMaps an option to the value stored in the model.
optionLabel(option: O) => stringString(option)Maps an option to a string for filtering and rendering.
optionFilter(option: O, query: Q) => booleansubstringCustom filter function. Q defaults to string.
idstringgeneratedBase id for accessibility attributes.
alignSelectedbooleanfalseAlign the dropdown so the selected option covers the trigger.
errorMessagesPartial<Record<HeadlessComboboxErrorCode, string>>n/aOverride default validation messages.

Scope

The render prop receives this scope object. The hook returns the same object.

State

Live values for the current selection and popup.

NameTypeDescription
isOpenbooleanWhether the dropdown is open.
multiplebooleanWhether multiple selection is enabled.
disabledbooleanWhether the control is disabled.
readonlybooleanWhether the control is read-only.
searchQueryQ | undefinedCurrent search query. Q defaults to string.
filteredOptionsT[]Options after applying the filter.
highlightedIndexnumberIndex of the highlighted option (-1 when none).
alignmentOffsetnumberPixel offset used for alignment.
cssAnchorNamestringUnique CSS anchor-name for popover positioning.
popupStyleHeadlessComboboxPopupStyleDefault popup positioning style. Spread or merge it onto the dropdown.
selectedCountnumberNumber of selected options.
selectedListV[]Selected values (single mode: a single-element array).
canSelectMorebooleanFalse when at maxLength (multiple).
isSelected(option: T) => booleanWhether an option is selected.
validbooleanWhether the current selection passes validation.
errorsHeadlessComboboxErrorCode[]Active validation errors ('required' | 'minlength' | 'maxlength').
validationMessagestringHuman-readable message for the first error.

ARIA prop bags

Spread a prop bag with `toReactProps`.

NameTypeDescription
triggerPropsHeadlessComboboxTriggerPropsrole=combobox, aria-expanded, aria-activedescendant, toggle and keydown handlers.
inputPropsHeadlessComboboxInputPropsSearch input attributes, aria-activedescendant, and keydown handling.
comboboxInputPropsHeadlessComboboxComboboxInputPropsTypeahead input attributes, open and focus handlers.
listboxPropsHeadlessComboboxListboxPropsrole=listbox and aria-multiselectable.
getOptionProps(option, index) => HeadlessComboboxOptionPropsrole=option, aria-selected, aria-disabled, and select and highlight handlers.

Actions

Methods that drive the combobox.

NameTypeDescription
toggle() => voidToggle the dropdown open or closed.
open() => voidOpen the dropdown.
close(returnFocus?: boolean) => voidClose the dropdown.
select(option: T) => voidSelect (single) or toggle (multiple) an option.
clear() => voidClear the selection (null or []).
setSearchQuery(value: Q | undefined) => voidUpdate the search query.
setHighlightedIndex(index: number) => voidSet the highlighted option. Wire it to hover to match keyboard behavior.
focusInput() => voidFocus the filter input while the popup stays open.
handleKeydown(event: KeyboardEvent) => voidKeyboard navigation handler.

Ref setters

Attach elements to the store. Bind only the elements your markup uses.

NameTypeDescription
setContainerRefref fnThe root container element.
setTriggerRefref fnThe trigger button or typeahead input.
setDropdownRefref fnThe dropdown popup element.
setInputRefref fnThe search input element.
setListRefref fnThe options list element.
setOptionRef(option, el) => voidEach option element. Needed for alignSelected and scroll-into-view.