Combobox
A recipe, not a package namespace. useCombobox owns open, value, input, highlight, and ids. Components own chrome. There is no Combobox.* export. One interactive role per root.
On this page
Presentation
useCombobox({ presentation: 'auto' }) picks a sheet on a coarse pointer or a narrow viewport and a popover otherwise, always a popover on the server and the first paint, through useSheetPresentation. Force popover or sheet when a docs screenshot must stay still.
If presentation flips while the list is open, the hook closes with blur.
The badge shows what useSheetPresentation picks here; isSheet is not isTouch.
import { Text, useSheetPresentation } from '@tounsoo/todae';
export default function PresentationBadge() {
const sheet = useSheetPresentation();
return (
<Text.Root>
{sheet.presentation} · isSheet={String(sheet.isSheet)}
</Text.Root>
);
}
popover · isSheet=false
Popover · single
Sibling Label.Root + Field.Root id. The input is the combobox. The list lives in Popover.Root.
import { ChevronDown } from 'lucide-react';
import {
Field,
Label,
OptionList,
Popover,
useCombobox,
useHighlight,
type ComboboxOption,
} from '@tounsoo/todae';
const FRAMEWORKS: ComboboxOption[] = [
{ value: 'react', label: 'React' },
{ value: 'redux', label: 'Redux' },
{ value: 'svelte', label: 'Svelte' },
];
function optionNodes(
items: ReturnType<typeof useCombobox>['items'],
getOptionProps: ReturnType<typeof useCombobox>['getOptionProps'],
) {
return items.map((item) => <OptionList.Option key={item.id} {...getOptionProps(item)} />);
}
export default function ComboboxSingle() {
const cb = useCombobox({
options: FRAMEWORKS,
presentation: 'popover',
defaultValue: 'react',
});
const found = useHighlight({ name: 'combobox-match', query: cb.query });
return (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>Framework</Label.Root>
<Field.Root {...cb.getAnchorProps()}>
<Field.TextInput {...cb.getInputProps()} />
<Field.Icon>
<ChevronDown />
</Field.Icon>
</Field.Root>
</Field.Group>
<Popover.Root {...cb.getPopoverProps()}>
<OptionList.Root ref={found.ref} {...cb.getListboxProps()}>
{optionNodes(cb.items, cb.getOptionProps)}
</OptionList.Root>
</Popover.Root>
</>
);
}
Popover · multi
Field.ChipInput via getChipInputProps. Chips are labels. Values dedupe.
import { ChevronDown } from 'lucide-react';
import {
Field,
Label,
OptionList,
Popover,
useCombobox,
useHighlight,
type ComboboxOption,
} from '@tounsoo/todae';
const TYPES: ComboboxOption[] = [
{ value: 'design', label: 'design' },
{ value: 'tokens', label: 'tokens' },
];
function optionNodes(
items: ReturnType<typeof useCombobox>['items'],
getOptionProps: ReturnType<typeof useCombobox>['getOptionProps'],
) {
return items.map((item) => <OptionList.Option key={item.id} {...getOptionProps(item)} />);
}
export default function ComboboxMulti() {
const cb = useCombobox({
selectionMode: 'multiple',
options: TYPES,
presentation: 'popover',
defaultValue: ['design'],
});
const found = useHighlight({ name: 'combobox-match', query: cb.query });
return (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>Type</Label.Root>
<Field.Root {...cb.getAnchorProps()}>
<Field.ChipInput {...cb.getChipInputProps()} />
<Field.Icon>
<ChevronDown />
</Field.Icon>
</Field.Root>
</Field.Group>
<Popover.Root {...cb.getPopoverProps()}>
<OptionList.Root ref={found.ref} {...cb.getListboxProps()}>
{optionNodes(cb.items, cb.getOptionProps)}
</OptionList.Root>
</Popover.Root>
</>
);
}
Sheet
The closed control is Button.Root. Search Field lives inside the sheet. Same inputValue and list as popover.
import { ChevronDown, Search } from 'lucide-react';
import {
BottomSheet,
Button,
Field,
Label,
OptionList,
useCombobox,
useHighlight,
type ComboboxOption,
} from '@tounsoo/todae';
const CITIES: ComboboxOption[] = [
{ value: 'sf', label: 'San Francisco' },
{ value: 'sj', label: 'San Jose' },
{ value: 'sc', label: 'Santa Clara' },
];
function optionNodes(
items: ReturnType<typeof useCombobox>['items'],
getOptionProps: ReturnType<typeof useCombobox>['getOptionProps'],
) {
return items.map((item) => <OptionList.Option key={item.id} {...getOptionProps(item)} />);
}
export default function ComboboxSheet() {
const cb = useCombobox({
options: CITIES,
presentation: 'sheet',
defaultValue: 'sf',
});
const found = useHighlight({ name: 'combobox-match', query: cb.query });
const selected = CITIES.find((city) => city.value === cb.value)?.label ?? 'Choose';
return (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>
City
</Label.Root>
<Button.Root {...cb.getTriggerProps()} variant="secondary">
{selected}
<Button.Icon>
<ChevronDown />
</Button.Icon>
</Button.Root>
</Field.Group>
<BottomSheet.Root {...cb.getSheetProps()}>
<BottomSheet.Grabber />
<BottomSheet.Body>
<Field.Group>
<Label.Root htmlFor={cb.ids.input}>Search</Label.Root>
<Field.Root id={cb.ids.input}>
<Field.Icon>
<Search />
</Field.Icon>
<Field.TextInput {...cb.getInputProps()} placeholder="Filter cities" />
</Field.Root>
</Field.Group>
<OptionList.Root ref={found.ref} {...cb.getListboxProps()}>
{optionNodes(cb.items, cb.getOptionProps)}
</OptionList.Root>
</BottomSheet.Body>
</BottomSheet.Root>
</>
);
}
Auto
One hook. The tree flips with the presentation. Force presentation when you need a still frame.
import {
BottomSheet,
Button,
Field,
Label,
OptionList,
Popover,
Stack,
Text,
useCombobox,
useHighlight,
type ComboboxOption,
} from '@tounsoo/todae';
const FRAMEWORKS: ComboboxOption[] = [
{ value: 'react', label: 'React' },
{ value: 'redux', label: 'Redux' },
{ value: 'svelte', label: 'Svelte' },
];
function optionNodes(
items: ReturnType<typeof useCombobox>['items'],
getOptionProps: ReturnType<typeof useCombobox>['getOptionProps'],
) {
return items.map((item) => <OptionList.Option key={item.id} {...getOptionProps(item)} />);
}
export default function ComboboxAuto() {
const cb = useCombobox({
options: FRAMEWORKS,
presentation: 'auto',
});
const found = useHighlight({ name: 'combobox-match', query: cb.query });
return (
<Stack.Root>
<Text.Root tone="muted">
presentation: {cb.presentation}
</Text.Root>
{cb.isSheet ? (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>
Framework
</Label.Root>
<Button.Root {...cb.getTriggerProps()} variant="secondary">
{FRAMEWORKS.find((item) => item.value === cb.value)?.label ?? 'Choose'}
</Button.Root>
</Field.Group>
<BottomSheet.Root {...cb.getSheetProps()}>
<BottomSheet.Body>
<Field.Root id={cb.ids.input} aria-label="Framework">
<Field.TextInput {...cb.getInputProps()} />
</Field.Root>
<OptionList.Root ref={found.ref} {...cb.getListboxProps()}>
{optionNodes(cb.items, cb.getOptionProps)}
</OptionList.Root>
</BottomSheet.Body>
</BottomSheet.Root>
</>
) : (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>Framework</Label.Root>
<Field.Root {...cb.getAnchorProps()}>
<Field.TextInput {...cb.getInputProps()} />
</Field.Root>
</Field.Group>
<Popover.Root {...cb.getPopoverProps()}>
<OptionList.Root ref={found.ref} {...cb.getListboxProps()}>
{optionNodes(cb.items, cb.getOptionProps)}
</OptionList.Root>
</Popover.Root>
</>
)}
</Stack.Root>
);
}
presentation: popover
Async
loadOptions(query, signal) loads options for the trimmed text, and they show as it returns them, so the loader does the matching; filterOptions is ignored beside it, and options only lends labels, such as the starting value's. A newer query aborts the last controller and discards a stale resolve. The hook keeps the previous list while loading is true. Debounce, loading, and Retry chrome stay in the recipe. The hook does not debounce.
Type fail to see the error row.
import { ChevronDown } from 'lucide-react';
import {
Button,
Field,
Label,
OptionList,
Popover,
Text,
useCombobox,
useHighlight,
type ComboboxOption,
} from '@tounsoo/todae';
const PACKAGES: ComboboxOption[] = [
{ value: 'todae', label: 'todae' },
{ value: 'tokens', label: 'tokens' },
];
function optionNodes(
items: ReturnType<typeof useCombobox>['items'],
getOptionProps: ReturnType<typeof useCombobox>['getOptionProps'],
) {
return items.map((item) => <OptionList.Option key={item.id} {...getOptionProps(item)} />);
}
function loadPackages(query: string, signal: AbortSignal): Promise<ComboboxOption[]> {
return new Promise((resolve, reject) => {
const timer = window.setTimeout(() => {
if (query.includes('fail')) {
reject(new Error('Couldn’t load options'));
return;
}
resolve(PACKAGES.filter((item) => item.label.toLowerCase().includes(query.trim().toLowerCase())));
}, 400);
signal.addEventListener('abort', () => {
window.clearTimeout(timer);
reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
});
});
}
export default function ComboboxAsync() {
const cb = useCombobox({
loadOptions: loadPackages,
presentation: 'popover',
});
const found = useHighlight({ name: 'combobox-match', query: cb.query });
return (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>Package</Label.Root>
<Field.Root {...cb.getAnchorProps()}>
<Field.TextInput {...cb.getInputProps()} placeholder="Type to load" />
<Field.Icon>
<ChevronDown />
</Field.Icon>
</Field.Root>
</Field.Group>
<Popover.Root {...cb.getPopoverProps()}>
{/* One status element for loading and errors; only its text changes. */}
<Text.Root role="status">{cb.loading ? 'Loading…' : cb.error ? 'Couldn’t load options.' : ''}</Text.Root>
{cb.error && !cb.loading ? (
<Button.Root variant="ghost" onClick={cb.retry}>
Retry
</Button.Root>
) : null}
{/* Keep the listbox mounted: the input's aria-controls points at it. */}
<OptionList.Root ref={found.ref} {...cb.getListboxProps()} hidden={cb.loading || cb.error != null}>
{optionNodes(cb.items, cb.getOptionProps)}
</OptionList.Root>
</Popover.Root>
</>
);
}
Empty and create
No matches render a status row. allowCreate adds one Create "{query}" option in the same OptionList when the query has no case-insensitive label match. Click or Enter commits. Single selects and closes. Multi adds a chip and stays open. onCreate may return a canonical value and should append the new option to options so the list can show it selected. It may return a promise: creating is true until it settles. What it throws or rejects with lands in createError while the text still asks for that label. Show both in a status element next to the create row, as the first create demo does; type fail there to see it.
import { ChevronDown } from 'lucide-react';
import {
Field,
Label,
OptionList,
Popover,
Text,
useCombobox,
useHighlight,
type ComboboxOption,
} from '@tounsoo/todae';
const PACKAGES: ComboboxOption[] = [
{ value: 'todae', label: 'todae' },
{ value: 'tokens', label: 'tokens' },
];
function optionNodes(
items: ReturnType<typeof useCombobox>['items'],
getOptionProps: ReturnType<typeof useCombobox>['getOptionProps'],
) {
return items.map((item) => <OptionList.Option key={item.id} {...getOptionProps(item)} />);
}
export default function ComboboxEmpty() {
const cb = useCombobox({
options: PACKAGES,
presentation: 'popover',
});
const found = useHighlight({ name: 'combobox-match', query: cb.query });
return (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>Package</Label.Root>
<Field.Root {...cb.getAnchorProps()}>
<Field.TextInput {...cb.getInputProps()} />
<Field.Icon>
<ChevronDown />
</Field.Icon>
</Field.Root>
</Field.Group>
<Popover.Root {...cb.getPopoverProps()}>
<Text.Root role="status">{cb.isEmpty ? 'No matches' : ''}</Text.Root>
{/* Keep the listbox mounted: the input's aria-controls points at it. */}
<OptionList.Root ref={found.ref} {...cb.getListboxProps()} hidden={cb.isEmpty}>
{optionNodes(cb.items, cb.getOptionProps)}
</OptionList.Root>
</Popover.Root>
</>
);
}
import { ChevronDown } from 'lucide-react';
import { useLayoutEffect, useState } from 'react';
import {
Field,
Label,
OptionList,
Popover,
Text,
useCombobox,
useHighlight,
type ComboboxOption,
} from '@tounsoo/todae';
const PACKAGES: ComboboxOption[] = [
{ value: 'todae', label: 'todae' },
{ value: 'tokens', label: 'tokens' },
];
function optionNodes(
items: ReturnType<typeof useCombobox>['items'],
getOptionProps: ReturnType<typeof useCombobox>['getOptionProps'],
) {
return items.map((item) => <OptionList.Option key={item.id} {...getOptionProps(item)} />);
}
/** The create row's words. The typed text sits between its quotes. */
const createLabel = (query: string) => `+ Create "${query}"`;
/**
* The options, then the create row. Matches are marked in the options only, and
* in the create row only the text it was typed for, so its own word "Create" is
* never marked. Both hooks share the name, so they paint as one.
*/
function MarkedOptions({ cb }: { cb: ReturnType<typeof useCombobox> }) {
const found = useHighlight({ name: 'combobox-match', query: cb.query });
const create = cb.items.find((item) => item.kind === 'create');
const asked = create?.kind === 'create' ? create.value : '';
const [row, setRow] = useState<HTMLElement | null>(null);
const [typed, setTyped] = useState<readonly Range[]>([]);
useLayoutEffect(() => {
// OptionList.Option renders its label last, as a bare text node; the browser test
// fails if that changes. (`Text` here is todae's component, so check the node type.)
// Mark only what is between the label's quotes.
const last = row?.lastChild;
const text = last?.nodeType === Node.TEXT_NODE ? (last as CharacterData) : null;
const at = text && asked !== '' ? text.data.indexOf(`"${asked}"`) : -1;
if (!text || at < 0) {
setTyped([]);
return;
}
const range = document.createRange();
range.setStart(text, at + 1);
range.setEnd(text, at + 1 + asked.length);
setTyped([range]);
}, [row, asked]);
useHighlight({ name: 'combobox-match', ranges: typed });
return (
<>
<div ref={found.ref} role="none" style={{ display: 'contents' }}>
{optionNodes(
cb.items.filter((item) => item.kind !== 'create'),
cb.getOptionProps,
)}
</div>
{create ? <OptionList.Option {...cb.getOptionProps(create)} ref={setRow} /> : null}
</>
);
}
function appendCreated(current: readonly ComboboxOption[], label: string): ComboboxOption[] {
if (current.some((item) => item.label.toLowerCase() === label.toLowerCase())) return [...current];
return [...current, { value: label, label }];
}
function savePackage(label: string): Promise<string> {
return new Promise((resolve, reject) => {
window.setTimeout(() => {
if (label.includes('fail')) reject(new Error('Couldn’t create the package'));
else resolve(label);
}, 400);
});
}
export default function ComboboxCreate() {
const [options, setOptions] = useState(PACKAGES);
const cb = useCombobox({
options,
allowCreate: true,
presentation: 'popover',
createLabel,
onCreate: async (label) => {
const saved = await savePackage(label);
setOptions((current) => appendCreated(current, saved));
return saved;
},
});
return (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>Package</Label.Root>
<Field.Root {...cb.getAnchorProps()}>
<Field.TextInput {...cb.getInputProps()} />
<Field.Icon>
<ChevronDown />
</Field.Icon>
</Field.Root>
</Field.Group>
<Popover.Root {...cb.getPopoverProps()}>
<OptionList.Root {...cb.getListboxProps()}>
<MarkedOptions cb={cb} />
</OptionList.Root>
{/* Under the create row; a load error would go in its own status. */}
<Text.Root role="status">
{cb.creating ? 'Creating…' : cb.createError ? 'Couldn’t create that package.' : ''}
</Text.Root>
</Popover.Root>
</>
);
}
import { ChevronDown } from 'lucide-react';
import { useLayoutEffect, useState } from 'react';
import {
Field,
Label,
OptionList,
Popover,
useCombobox,
useHighlight,
type ComboboxOption,
} from '@tounsoo/todae';
const PACKAGES: ComboboxOption[] = [
{ value: 'todae', label: 'todae' },
{ value: 'tokens', label: 'tokens' },
];
function optionNodes(
items: ReturnType<typeof useCombobox>['items'],
getOptionProps: ReturnType<typeof useCombobox>['getOptionProps'],
) {
return items.map((item) => <OptionList.Option key={item.id} {...getOptionProps(item)} />);
}
/** The create row's words. The typed text sits between its quotes. */
const createLabel = (query: string) => `+ Create "${query}"`;
/**
* The options, then the create row. Matches are marked in the options only, and
* in the create row only the text it was typed for, so its own word "Create" is
* never marked. Both hooks share the name, so they paint as one.
*/
function MarkedOptions({ cb }: { cb: ReturnType<typeof useCombobox> }) {
const found = useHighlight({ name: 'combobox-match', query: cb.query });
const create = cb.items.find((item) => item.kind === 'create');
const asked = create?.kind === 'create' ? create.value : '';
const [row, setRow] = useState<HTMLElement | null>(null);
const [typed, setTyped] = useState<readonly Range[]>([]);
useLayoutEffect(() => {
// OptionList.Option renders its label last, as a bare text node; the browser test
// fails if that changes. (`Text` here is todae's component, so check the node type.)
// Mark only what is between the label's quotes.
const last = row?.lastChild;
const text = last?.nodeType === Node.TEXT_NODE ? (last as CharacterData) : null;
const at = text && asked !== '' ? text.data.indexOf(`"${asked}"`) : -1;
if (!text || at < 0) {
setTyped([]);
return;
}
const range = document.createRange();
range.setStart(text, at + 1);
range.setEnd(text, at + 1 + asked.length);
setTyped([range]);
}, [row, asked]);
useHighlight({ name: 'combobox-match', ranges: typed });
return (
<>
<div ref={found.ref} role="none" style={{ display: 'contents' }}>
{optionNodes(
cb.items.filter((item) => item.kind !== 'create'),
cb.getOptionProps,
)}
</div>
{create ? <OptionList.Option {...cb.getOptionProps(create)} ref={setRow} /> : null}
</>
);
}
function appendCreated(current: readonly ComboboxOption[], label: string): ComboboxOption[] {
if (current.some((item) => item.label.toLowerCase() === label.toLowerCase())) return [...current];
return [...current, { value: label, label }];
}
export default function ComboboxCreateMulti() {
const [options, setOptions] = useState(PACKAGES);
const cb = useCombobox({
selectionMode: 'multiple',
options,
allowCreate: true,
presentation: 'popover',
createLabel,
onCreate: (label) => {
setOptions((current) => appendCreated(current, label));
return label;
},
});
return (
<>
<Field.Group>
<Label.Root {...cb.getLabelProps()}>Tags</Label.Root>
<Field.Root {...cb.getAnchorProps()}>
<Field.ChipInput {...cb.getChipInputProps()} />
<Field.Icon>
<ChevronDown />
</Field.Icon>
</Field.Root>
</Field.Group>
<Popover.Root {...cb.getPopoverProps()}>
<OptionList.Root {...cb.getListboxProps()}>
<MarkedOptions cb={cb} />
</OptionList.Root>
</Popover.Root>
</>
);
}
Highlight matches
Every demo on this page marks the typed text in its options with useHighlight, which paints it without changing the options' markup, so each option keeps its accessible name. Pass the hook's query (empty while the input shows the selected label, so nothing is marked then) and put the ref on the list:
const found = useHighlight({ name: 'combobox-match', query: cb.query });
<OptionList.Root ref={found.ref} {...cb.getListboxProps()}>
Hooks that share a name paint together, so give every combobox the same name and style it once:
::highlight(combobox-match) {
background-color: var(--todae-color-status-warning-bg);
color: var(--todae-color-fg-default);
}
With loadOptions, the loader does the matching, so a row it returns may not hold the typed text and shows no mark.
A create row's label holds the typed text inside its own words, so a search of the whole list would also mark letters of a word like "Create". The create demos put the hook's ref on a role="none" wrapper around the options only, and mark the create row with a second hook under the same name, whose ranges cover just the text between the label's quotes.
Composition rules
- Sibling Label +
Field.Rootid. NoField.Label. - Do not spread usePopover
getTriggerPropsnext togetAnchorProps. Dual-wire is a QA fail. - OptionList is the overlay list. Do not also render Radio or Checkbox for the same value.
- Do not bake combobox into Field. Do not export
Combobox.*chrome. - Sheet trigger uses
aria-haspopup="dialog". Popover Field chrome has noaria-haspopup.
Accessible composition
Todae handles: useCombobox makes the input a role="combobox" that points at the listbox with aria-controls and at the active option with aria-activedescendant, and runs the arrow keys, Home, End, Enter, Escape and Tab. OptionList renders role="listbox" with role="option" rows carrying aria-selected and aria-disabled, and aria-multiselectable in multi mode. Popover and BottomSheet close on Escape and return focus. In multi mode, Field.ChipInput names each chip's remove button.
You supply: The label: a Label with {...cb.getLabelProps()}, which points it at the input, or at the trigger in sheet mode, and gives it the id the listbox takes its name from. Inside a sheet, the search field's own name, such as aria-label on its Field.Root. With no visible label, pass aria-label to getListboxProps(). In sheet mode, trigger text that shows the value. Loading, error, create failure and empty text in a role="status" element; keep that element mounted and change its text, since text in a region that has just appeared is not always read. A Retry button that is a real button, as in the async demo.
Watch for: Unmounting OptionList.Root when it is empty or loading; set hidden so aria-controls still points at it. Your own onKeyDown, onFocus or onBlur after the getter's spread, which replaces the hook's handlers. The match highlight as the only cue: it is visual only.
When to use
When: Picking one or more values from a list long enough that people type to find one, such as a country, an assignee or tags.
When not: A few options that fit on the page → Radio or Checkbox. One value from a short list in a form → Field.Select. A short overlay list with no typing → usePopover and OptionList. Running actions → Menu, or the Command palette recipe to search them. Free text with no list → a Field text input.
Hooks
When to use them, and their props, are on useCombobox and useSheetPresentation.