Combobox
A text field that filters a list and holds one option. Pick it for long lists, for options fetched as the reader types, and for lists the reader may add to. A short fixed list reads better in a select; free text with no list is a plain input.
Install
npx shadcn@latest add https://thrumui.dev/r/combobox.jsonAdds components/ui/combobox.tsx and installs @base-ui/react@1.9.0. Nothing else in your project changes.
import { Combobox } from "@/components/ui/combobox";Automatically installs icons check, chevron-down, loader-circle, plus and x from the icon set.
Data shape
type ComboboxOption = { value: string; label: string; disabled?: boolean };
type ComboboxOptionGroup = { label: string; items: readonly ComboboxOption[] };
// items: ComboboxOption[] or ComboboxOptionGroup[]const WAREHOUSES = [
{ value: "berlin", label: "Berlin" },
{ value: "oslo", label: "Oslo", disabled: true },
{ value: "toronto", label: "Toronto" },
];Props
| Prop | Type | Default | Description |
|---|---|---|---|
Combobox: items | ComboboxOption[] | ComboboxOptionGroup[] | – | Every option, or groups of them. The field filters them as the reader types and shows the selected option's label. |
Combobox: value | ComboboxOption | null | – | The selected option, when the parent holds it. Use it with onValueChange. |
Combobox: defaultValue | ComboboxOption | null | – | The option selected at first, when the combobox holds it itself. |
Combobox: onValueChange | (value: ComboboxOption | null) => void | – | Called with the picked option, or null when the field is cleared. |
Combobox: onInputValueChange | (text: string) => void | – | Called with the typed text. Fetch matching options here and pass them as items. |
Combobox: filter | ((item, query) => boolean) | null | – | How options are matched. The default keeps labels that contain the text, ignoring case and accents. null shows items as given, for a list filtered by a server. |
Combobox: loading | boolean | Default false | Results are on their way: the list shows the loading row instead of the empty row and is marked busy. |
Combobox: loadingLabel | string | Default "Loading…" | The text of the loading row. |
Combobox: allowCreate | boolean | Default false | Add Create "text" to the list when the text matches no option exactly. Works with a flat list of options. |
Combobox: onCreate | (text: string) => void | – | Called with the text when the create option is picked. The new option is selected and stays in the list. |
Combobox: disabled | boolean | Default false | The whole field is dimmed and cannot be used. |
Combobox: name | string | – | The field name when the combobox sits in a form. The selected option's value is sent. |
Combobox: sound | boolean | Default true | Play a soft sound when the list opens or closes and a click when an option is picked, if the visitor has sound on. |
ComboboxInput: size | "sm" | "md" | "lg" | Default "md" | 28, 32 or 40 pixels tall. |
ComboboxInput: showClear | boolean | Default true | Show a button that clears the value while there is one. |
ComboboxInput: clearLabel | string | Default "Clear" | The name of the clear button. |
ComboboxInput: showTrigger | boolean | Default true | Show the chevron button that opens the list. |
ComboboxInput: className | string | – | Sets the width. The field fills its container by default. |
ComboboxContent | popup props | – | The panel. As wide as the field, at most 352 pixels tall, then it scrolls. |
ComboboxList | (item) => ReactNode | – | Draws each filtered option or group. |
ComboboxItem: value | ComboboxOption | Required | The option this row stands for. |
ComboboxItem: disabled | boolean | Default false | Shown, but it cannot be picked and the arrow keys skip it. |
ComboboxGroup: items | ComboboxOption[] | – | The group's options, drawn by ComboboxCollection. |
ComboboxLabel, ComboboxCollection, ComboboxSeparator | part props | – | A group's heading, the drawing of its filtered options, and a line between groups. |
ComboboxEmpty: children | ReactNode | Default "No results" | The row shown when nothing matches. Hidden while loading. |
Motion and sound
Motion
- The list fades in and grows from 96% to full size over 150 ms, from the edge that touches the field, and plays it backwards to close.
- The chevron turns over 150 ms while the list is open. The loading row's ring turns until the results arrive.
- Reduced motion: the list appears and leaves at once, and the ring stands still.
Sound
- A soft rising tone when the list opens and a falling one when it closes without a pick.
- A click when an option is picked. That press makes no second sound for the closing list.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- It follows the WAI-ARIA combobox pattern with list autocomplete: the input is a combobox that controls a listbox, and the highlighted option is announced while the focus stays in the text.
- The input needs a name: a label element, or an aria-label on ComboboxInput.
- The selected option carries a tick as well as aria-selected. The clear button is named Clear and the chevron Show options.
- The loading row and the empty row sit in live regions, so a screen reader hears Loading… and No results.
- A long label wraps in the list and is cut in the field. Nothing overflows at 160 pixels wide.
- Under a glass material the list is translucent. Its tint keeps the text at 4.5 to 1 over any page.
| Keys | Action |
|---|---|
| Type | Filter the list. It opens with the first keystroke. |
| ↓ / ↑ | Open the list, then move the highlight. Disabled options are skipped. Past either end the focus returns to the text. |
| Home / End | Move the caret in the text. |
| Enter | Pick the highlighted option and close the list. On the create option, create it. |
| Esc | Close the list. A second Esc clears the text the reader typed. |
| Tab | Leave the field. The text returns to the selected option's label. |
Source
"use client";
import { createContext, useContext, useState, type ReactNode } from "react";
import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox";
import { cn } from "@/lib/utils";
import { CheckIcon } from "@/components/icons/check";
import { ChevronDownIcon } from "@/components/icons/chevron-down";
import { LoaderCircleIcon } from "@/components/icons/loader-circle";
import { PlusIcon } from "@/components/icons/plus";
import { XIcon } from "@/components/icons/x";
import { play } from "@/lib/thrum-sound";
/** The shape of an option. Base UI reads `label` for the field's text and `value` for a form. */
export type ComboboxOption = { value: string; label: string; disabled?: boolean };
/** A group of options under a heading, for `items`. */
export type ComboboxOptionGroup<Option = ComboboxOption> = { label: string; items: readonly Option[] };
/** The option `allowCreate` adds to the list. Picking it creates `create`. */
type CreateOption = ComboboxOption & { create: string };
const isCreate = (item: unknown): item is CreateOption => typeof item === "object" && item !== null && typeof (item as CreateOption).create === "string";
type Shared = { loading: boolean; loadingLabel: string };
const SharedContext = createContext<Shared>({ loading: false, loadingLabel: "Loading…" });
export type ComboboxProps<Value> = ComboboxPrimitive.Root.Props<Value> & {
/** Results are being fetched: the list shows a loading row instead of its empty row, and is marked busy. */
loading?: boolean;
/** The text of the loading row. */
loadingLabel?: string;
/** Offer `Create "text"` when the typed text matches no option exactly. Needs flat `items` of `{ value, label }`. */
allowCreate?: boolean;
/** Called with the typed text when the create option is picked. The new option is selected and kept in the list. */
onCreate?: (text: string) => void;
/** Play a soft sound when the list opens or closes and a click when an option is picked, if the visitor has sound on. */
sound?: boolean;
};
/**
* A text field that filters a list of options and holds one of them. Use it for long lists, lists loaded as the reader types,
* and lists the reader may add to. For a short fixed list, a select is simpler. Name the input with a `<label>` or an `aria-label`.
*/
export function Combobox<Value>({
loading = false,
loadingLabel = "Loading…",
allowCreate = false,
onCreate,
sound = true,
items,
value,
defaultValue,
onValueChange,
onOpenChange,
inputValue,
onInputValueChange,
...props
}: ComboboxProps<Value>) {
const [own, setOwn] = useState<Value | null>(defaultValue ?? null);
const [typed, setTyped] = useState("");
// Options made with "Create" stay in the list, so the field can show the one it holds.
const [created, setCreated] = useState<ComboboxOption[]>([]);
const selected = value !== undefined ? value : own;
const query = String(inputValue ?? typed).trim();
let shown = items;
if (allowCreate && Array.isArray(items) && !items.some((item) => item && typeof item === "object" && "items" in item)) {
const flat = [...(items as unknown as ComboboxOption[]), ...created.filter((option) => !(items as unknown as ComboboxOption[]).some((item) => item.value === option.value))];
const lower = query.toLocaleLowerCase();
const exact = flat.some((item) => String(item.label ?? item).toLocaleLowerCase() === lower);
const offer: CreateOption[] = query && !exact ? [{ value: `\u0000create:${query}`, label: `Create "${query}"`, create: query }] : [];
shown = [...flat, ...offer] as unknown as typeof items;
}
return (
<SharedContext.Provider value={{ loading, loadingLabel }}>
<ComboboxPrimitive.Root<Value>
items={shown}
value={selected}
inputValue={inputValue}
onInputValueChange={(next, details) => {
setTyped(next);
onInputValueChange?.(next, details);
}}
onOpenChange={(open, details) => {
// Picking an option also closes the list. That press gets the pick's click, not a second sound.
if (sound && details.reason !== "item-press") play(open ? "open" : "close");
onOpenChange?.(open, details);
}}
onValueChange={(next, details) => {
let picked = next;
if (isCreate(next)) {
const option: ComboboxOption = { value: next.create, label: next.create };
setCreated((list) => [...list, option]);
onCreate?.(next.create);
picked = option as Value;
}
if (sound && picked !== null) play("select");
setOwn(picked);
onValueChange?.(picked, details);
}}
{...props}
/>
</SharedContext.Provider>
);
}
export type ComboboxInputProps = Omit<ComboboxPrimitive.Input.Props, "size"> & {
/** `sm` is 28 pixels tall, `md` 32, `lg` 40. */
size?: "sm" | "md" | "lg";
/** Show a button that clears the value while there is one. */
showClear?: boolean;
/** The name of the clear button. */
clearLabel?: string;
/** Show the chevron button that opens the list. */
showTrigger?: boolean;
};
const HEIGHT = { sm: "h-7", md: "h-8", lg: "h-10" } as const;
const SMALL_BUTTON =
"grid size-6 flex-none cursor-pointer place-items-center rounded-sm text-muted-foreground transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none hover:bg-accent hover:text-accent-foreground focus-visible:outline-2 focus-visible:outline-ring data-disabled:pointer-events-none [&_svg]:size-4";
/** The field: the text input, a clear button while there is a value, and a chevron that opens the list. */
export function ComboboxInput({ size = "md", showClear = true, clearLabel = "Clear", showTrigger = true, className, ...props }: ComboboxInputProps) {
return (
<ComboboxPrimitive.InputGroup
data-slot="combobox"
data-surface="control"
className={cn(
"flex w-full min-w-0 items-center gap-1 rounded-md border border-input bg-background ps-2.5 pe-1 text-foreground",
"transition-[border-color] duration-150 ease-out motion-reduce:transition-none",
"has-[input:focus-visible]:outline-2 has-[input:focus-visible]:-outline-offset-1 has-[input:focus-visible]:outline-ring has-[input[aria-invalid=true]]:border-destructive",
"has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50",
HEIGHT[size],
className,
)}
>
<ComboboxPrimitive.Input
data-slot="combobox-input"
// 16px text on phones: anything smaller makes iOS zoom the page when the field takes focus.
className="h-full min-w-0 flex-1 bg-transparent text-base text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed md:text-sm"
{...props}
/>
{showClear && (
<ComboboxPrimitive.Clear data-slot="combobox-clear" aria-label={clearLabel} className={SMALL_BUTTON}>
<XIcon />
</ComboboxPrimitive.Clear>
)}
{showTrigger && (
<ComboboxPrimitive.Trigger data-slot="combobox-trigger" aria-label="Show options" className={cn(SMALL_BUTTON, "[&_svg]:transition-[rotate] [&_svg]:duration-150 data-popup-open:[&_svg]:rotate-180 motion-reduce:[&_svg]:transition-none")}>
<ChevronDownIcon />
</ComboboxPrimitive.Trigger>
)}
</ComboboxPrimitive.InputGroup>
);
}
/**
* The list's panel. It opens under the field, as wide as the field, and scrolls when it is taller than the space it has.
* It is a floating surface, so it turns to glass when the page's material asks for it. While loading it shows a loading row.
*/
export function ComboboxContent({ className, children, ...props }: ComboboxPrimitive.Popup.Props) {
const { loading, loadingLabel } = useContext(SharedContext);
return (
<ComboboxPrimitive.Portal>
<ComboboxPrimitive.Positioner sideOffset={4} collisionPadding={8} className="z-50 outline-none">
<ComboboxPrimitive.Popup
data-slot="combobox-content"
data-surface="floating"
aria-busy={loading || undefined}
className={cn(
"max-h-[min(var(--available-height),22rem)] w-(--anchor-width) max-w-(--available-width) min-w-40 origin-(--transform-origin) scroll-py-2 overflow-y-auto overscroll-contain rounded-lg border bg-popover p-2 text-popover-foreground shadow-md outline-none",
"transition-[opacity,scale] duration-150 ease-out data-ending-style:scale-[0.96] data-ending-style:opacity-0 data-starting-style:scale-[0.96] data-starting-style:opacity-0 motion-reduce:transition-none",
className,
)}
{...props}
>
{/* Always in the page, so its changes are announced. */}
<ComboboxPrimitive.Status data-slot="combobox-status" className="text-sm text-muted-foreground">
{loading && (
<span className="flex min-h-8 items-center gap-2 px-2">
<LoaderCircleIcon className="size-4 flex-none animate-spin motion-reduce:animate-none" />
{loadingLabel}
</span>
)}
</ComboboxPrimitive.Status>
{children}
</ComboboxPrimitive.Popup>
</ComboboxPrimitive.Positioner>
</ComboboxPrimitive.Portal>
);
}
/** The options. Pass a function that draws one item: `{(item) => <ComboboxItem value={item}>{item.label}</ComboboxItem>}`. */
export function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
return <ComboboxPrimitive.List data-slot="combobox-list" className={cn("outline-none", className)} {...props} />;
}
/** One option. A tick marks the selected one; the create option shows a plus. */
export function ComboboxItem({ className, children, value, ...props }: ComboboxPrimitive.Item.Props) {
const create = isCreate(value);
return (
<ComboboxPrimitive.Item
data-slot="combobox-item"
data-create={create ? "" : undefined}
value={value}
className={cn(
"grid min-h-8 cursor-default grid-cols-[1fr_1rem] items-center gap-2 rounded-sm py-1.5 ps-2 pe-2 text-sm outline-none select-none",
"data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-50",
create && "grid-cols-[1rem_1fr]",
className,
)}
{...props}
>
{create ? (
<>
<PlusIcon className="size-4 text-muted-foreground" />
<span className="min-w-0 break-words">{children}</span>
</>
) : (
<>
<span className="min-w-0 break-words">{children}</span>
{/* The tick marks the selected option, so selection never rests on the highlight colour. */}
<ComboboxPrimitive.ItemIndicator className="[&_svg]:size-4">
<CheckIcon />
</ComboboxPrimitive.ItemIndicator>
</>
)}
</ComboboxPrimitive.Item>
);
}
/** Options that belong together, under a `ComboboxLabel`. Pass the group's `items` and draw them with `ComboboxCollection`. */
export function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
return <ComboboxPrimitive.Group data-slot="combobox-group" className={cn("not-last:mb-1", className)} {...props} />;
}
export function ComboboxLabel({ className, ...props }: ComboboxPrimitive.GroupLabel.Props) {
return <ComboboxPrimitive.GroupLabel data-slot="combobox-label" className={cn("px-2 py-1.5 text-xs font-medium text-muted-foreground", className)} {...props} />;
}
/** Draws the filtered items of the group it sits in. */
export function ComboboxCollection(props: ComboboxPrimitive.Collection.Props) {
return <ComboboxPrimitive.Collection {...props} />;
}
export function ComboboxSeparator({ className, ...props }: ComboboxPrimitive.Separator.Props) {
return <ComboboxPrimitive.Separator data-slot="combobox-separator" className={cn("-mx-2 my-1 h-px bg-border", className)} {...props} />;
}
/** The row shown when nothing matches. Hidden while the list is loading. */
export function ComboboxEmpty({ className, children = "No results", ...props }: Omit<ComboboxPrimitive.Empty.Props, "children"> & { children?: ReactNode }) {
const { loading } = useContext(SharedContext);
return (
<ComboboxPrimitive.Empty data-slot="combobox-empty" className={cn("text-sm text-muted-foreground", className)} {...props}>
{loading ? null : <span className="flex min-h-8 items-center px-2">{children}</span>}
</ComboboxPrimitive.Empty>
);
}Files and dependencies
- Adds
components/ui/combobox.tsx- Packages
@base-ui/react@1.9.0- Brings along
- Sound engine
- Icons
checkchevron-downloader-circleplusx
Changelog
- 1.0.0 · 2026-12-03First release.