Components
Combobox
A button that looks like a Select and opens a list with a search box, to pick one option or several from a long list.
Introduction
Combobox is for choosing from a list too long to scan: people to assign, countries, frameworks. It looks like a Select, a button that shows the pick and a chevron, but the list it opens starts with a search box, so the user can type to narrow it down.
- Pick one option (the default), or set
selectionMode="multiple"to pick several. - With several picks the button names them, or counts them once there are more than
maxLabels, as in "3 selected". - An option can carry an icon or an avatar and a second line of text. Individual options can be disabled.
- The value is the
idof the pick, or an array of them, and it works in a form.
For a short list without search, use Select. For a text field that suggests as you type, use Autocomplete.
Installation
centerUI has no CLI or registry yet: components are copied into your project. Combobox uses Button for its trigger and Avatar for avatars.
# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components tailwind-variants tailwind-merge clsxAdd Button first (see its Manual installation), then follow the steps below.
Manual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the Avatar file
It shows the picture of an option that has an avatar. Skip it and remove the import if you do not need avatars.
src/components/ui/avatar/avatar.tsxShow code
"use client";
import Image from "next/image";
import { Children, type ReactNode, useState } from "react";
import { UserIcon } from "@/components/icons";
import { cn } from "@/lib/cn";
import {
AvatarGroupProvider,
useAvatarGroup,
} from "@/types/avatar-group-context";
import { avatarGroupStyles, avatarStyles } from "@/types/avatar-styles";
type Size = "xs" | "sm" | "md" | "lg" | "xl";
// The size in pixels, so the image is requested at the size it is drawn.
const pixels: Record<Size, number> = { xs: 20, sm: 24, md: 32, lg: 40, xl: 56 };
export interface AvatarProps {
/** Image URL. Falls back to the initials of `name` if missing or if it fails to load. */
src?: string;
/** Used for the initials. Also the accessible name when the avatar has a `status`. */
name?: string;
/** Describes the image. Leave it out when the name is written next to the avatar. */
alt?: string;
/** Shown when there is no image and no `name`. Defaults to a person icon. */
fallback?: ReactNode;
size?: Size;
shape?: "circle" | "square";
/** A small dot on the corner. */
status?: "online" | "away" | "busy" | "offline";
className?: string;
}
function initialsOf(name?: string) {
if (!name) return "";
return name
.trim()
.split(/\s+/)
.slice(0, 2)
.map((word) => word[0]?.toUpperCase() ?? "")
.join("");
}
/**
* A small picture of a person or thing. When there is no picture, or it fails
* to load, it shows the initials of `name`, then `fallback`, then a person
* icon. It is decorative unless you pass `alt` (or a `status`), because the
* name is normally written next to it.
*
* Inside an `AvatarGroup` it takes its size and shape from the group.
*
* @example
* <Avatar src="/ana.png" name="Ana Wijaya" status="online" />
*/
export function Avatar({
src,
name,
alt,
fallback,
size,
shape,
status,
className,
}: AvatarProps) {
const group = useAvatarGroup();
// Remember which URL failed, so a new `src` gets its own chance.
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const showImage = Boolean(src) && failedSrc !== src;
const resolvedSize = size ?? group?.size ?? "sm";
const styles = avatarStyles({
size: resolvedSize,
shape: shape ?? group?.shape,
status,
grouped: group ? true : undefined,
});
const initials = initialsOf(name);
const content =
showImage && src ? (
<Image
src={src}
alt=""
width={pixels[resolvedSize]}
height={pixels[resolvedSize]}
unoptimized
onError={() => setFailedSrc(src)}
className={styles.image()}
/>
) : (
initials ||
fallback || <UserIcon className="size-1/2" aria-hidden="true" />
);
// A status is information, so it is spoken along with the name.
const label = alt ?? (status ? name : undefined);
const spoken = label ? (status ? `${label}, ${status}` : label) : undefined;
const classes = cn(styles.root(), className);
const inner = (
<>
<span className={styles.frame()}>{content}</span>
{status ? <span aria-hidden="true" className={styles.status()} /> : null}
</>
);
if (spoken) {
return (
<span role="img" aria-label={spoken} className={classes}>
{inner}
</span>
);
}
return (
<span aria-hidden="true" className={classes}>
{inner}
</span>
);
}
export interface AvatarGroupProps {
/** The avatars. */
children: ReactNode;
/** Show at most this many avatars, then a "+N" for the rest. */
max?: number;
/** Passed down to every avatar in the group. */
size?: Size;
/** Passed down to every avatar in the group. */
shape?: "circle" | "square";
/** Names the group for screen readers, for example "Project members". */
"aria-label"?: string;
className?: string;
}
/**
* Avatars in an overlapping row, for members of a team or people in a thread.
* The group sets the size and shape of the avatars inside it, and with `max`
* it shows the first few and a "+N" for the rest.
*
* @example
* <AvatarGroup max={3} aria-label="Project members">
* <Avatar name="Ana Wijaya" />
* <Avatar name="Budi Santoso" />
* </AvatarGroup>
*/
export function AvatarGroup({
children,
max,
size = "sm",
shape = "circle",
className,
...props
}: AvatarGroupProps) {
const all = Children.toArray(children);
const shown = max !== undefined && all.length > max ? all.slice(0, max) : all;
const hidden = all.length - shown.length;
return (
<AvatarGroupProvider value={{ size, shape }}>
{/* biome-ignore lint/a11y/useSemanticElements: a div with role="group" is the standard pattern for a labelled set of avatars; <fieldset> brings form styling quirks. */}
<div
role="group"
aria-label={props["aria-label"]}
className={cn(avatarGroupStyles({ size }), className)}
>
{shown}
{hidden > 0 ? (
<Avatar
fallback={`+${hidden}`}
alt={`${hidden} more`}
className="[&>span]:bg-muted [&>span]:text-fg"
/>
) : null}
</div>
</AvatarGroupProvider>
);
}2. Add the Combobox file
src/components/ui/combobox/combobox.tsxShow code
"use client";
import { type ReactNode, useContext, useState } from "react";
import {
Select as AriaSelect,
type SelectProps as AriaSelectProps,
Autocomplete,
FieldError,
Input,
type Key,
Label,
ListBox,
ListBoxItem,
Popover,
SearchField,
SelectStateContext,
SelectValue,
Text,
useFilter,
type ValidationResult,
} from "react-aria-components";
import { CheckIcon, ChevronsUpDownIcon, SearchIcon } from "@/components/icons";
import { Avatar, type AvatarProps } from "@/components/ui/avatar/avatar";
import { Button } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
/** One option of a Combobox. */
export interface ComboboxItem {
/** What goes in the value when it is picked. Unique. */
id: string;
/** The text of the option, shown in the button when it is picked, and what searching matches. */
label: string;
/** A smaller line under the label in the list. */
description?: ReactNode;
/** An icon before the label, in the list and in the button. */
icon?: ReactNode;
/** An avatar before the label, in the list and in the button. */
avatar?: AvatarProps;
isDisabled?: boolean;
}
type Mode = "single" | "multiple";
export interface ComboboxProps<M extends Mode = "single"> {
label?: ReactNode;
/** Help text under the field. */
description?: ReactNode;
/** Shown when the field is invalid. A function receives the validation result. */
errorMessage?: string | ((validation: ValidationResult) => string);
/** Shown in the button while nothing is picked. */
placeholder?: string;
/** The options. */
items: ComboboxItem[];
/** One pick (`"single"`, the default), or several. */
selectionMode?: M;
/** The `id` of the pick (or of every pick with `"multiple"`), for a controlled field. */
value?: M extends "multiple" ? string[] : string | null;
/** The pick to start with, for an uncontrolled field. */
defaultValue?: M extends "multiple" ? string[] : string | null;
onChange?: (value: M extends "multiple" ? string[] : string | null) => void;
/** With several picks: how many are named in the button before it says "3 selected". Defaults to 2. */
maxLabels?: number;
/** With several picks: the most that can be picked. The other options are disabled until one is removed. */
maxSelected?: number;
/** Add a footer to the list with a button that removes every pick. Defaults to `true`. */
isClearable?: boolean;
/** Placeholder of the search box. */
searchPlaceholder?: string;
/** Shown when nothing matches the search. */
emptyMessage?: string;
/** Look of the button. */
variant?: "outline" | "secondary" | "ghost";
/** Size of the button. */
size?: React.ComponentProps<typeof Button>["size"];
/** The pick is submitted with a form under this name, as its `id` (one entry per pick). */
name?: string;
autoFocus?: boolean;
isDisabled?: boolean;
isInvalid?: boolean;
isRequired?: boolean;
"aria-label"?: string;
className?: string;
}
// A footer inside the list, with a count and a button that removes every pick.
function Footer({ isMultiple }: { isMultiple: boolean }) {
const state = useContext(SelectStateContext);
const count = isMultiple
? Array.isArray(state?.value)
? state.value.length
: 0
: state?.value != null
? 1
: 0;
if (!state || count === 0) return null;
return (
<div className="flex items-center justify-between gap-2 border-t px-3 py-1.5 text-xs text-muted-fg">
<span>{isMultiple ? `${count} selected` : "1 selected"}</span>
<Button
size="xs"
variant="ghost"
onPress={() => {
(state as { setValue: (value: Key | Key[] | null) => void }).setValue(
isMultiple ? [] : null,
);
}}
>
Clear
</Button>
</div>
);
}
/**
* A field for picking from a long list. It looks like a Select: a button that
* shows what is picked, and opens a list. The list has a search box, so the
* user can type to narrow it down. Built on react-aria's Select, with its
* Autocomplete filtering: the arrow keys move through the list, typing in the
* search box filters it, and Escape closes it.
*
* Pick one option (the default), or set `selectionMode="multiple"` for several.
* With several, the list stays open with a check mark on each option that is
* taken, and the button names them, or counts them when there are many.
*
* @example
* <Combobox label="Country" items={countries} placeholder="Choose a country" />
* <Combobox label="Topics" items={topics} selectionMode="multiple" />
*/
export function Combobox<M extends Mode = "single">({
label,
description,
errorMessage,
placeholder,
items,
selectionMode,
value,
defaultValue,
onChange,
maxLabels = 2,
maxSelected,
isClearable = true,
searchPlaceholder = "Search…",
emptyMessage = "No results found.",
variant = "outline",
size,
name,
autoFocus,
isDisabled,
isInvalid,
isRequired,
className,
...props
}: ComboboxProps<M>) {
const { contains } = useFilter({ sensitivity: "base" });
const isMultiple = selectionMode === "multiple";
// The field always hands its value to react-aria, so it can tell how many
// are picked (for maxSelected) even when the caller does not control it.
const [inner, setInner] = useState(
defaultValue !== undefined ? defaultValue : isMultiple ? [] : null,
);
const current = value !== undefined ? value : inner;
const picked: string[] = Array.isArray(current) ? current : [];
const isFull =
isMultiple && maxSelected !== undefined && picked.length >= maxSelected;
const disabledKeys = items
.filter((item) => item.isDisabled || (isFull && !picked.includes(item.id)))
.map((item) => item.id);
const listProps = {
value: current,
onChange: (next: Key | Key[] | null) => {
const change = onChange as
| ((value: string | string[] | null) => void)
| undefined;
const normalized = Array.isArray(next)
? next.map(String)
: next === null
? null
: String(next);
setInner(normalized as typeof inner);
change?.(normalized);
},
} as unknown as Partial<AriaSelectProps<ComboboxItem, Mode>>;
return (
<AriaSelect<ComboboxItem, Mode>
{...listProps}
selectionMode={isMultiple ? "multiple" : "single"}
disabledKeys={disabledKeys}
aria-label={label ? undefined : props["aria-label"]}
placeholder={placeholder}
name={name}
autoFocus={autoFocus}
isDisabled={isDisabled}
isInvalid={isInvalid}
isRequired={isRequired}
className={cn("group/combobox flex w-full flex-col gap-1.5", className)}
>
{label ? (
<Label className="text-sm font-medium group-data-required/combobox:after:ml-0.5 group-data-required/combobox:after:text-danger group-data-required/combobox:after:content-['*']">
{label}
</Label>
) : null}
<Button
variant={variant}
size={size}
className="w-full justify-between text-left font-normal group-data-invalid/combobox:border-danger"
>
<SelectValue className="flex min-w-0 flex-1 items-center gap-2 data-placeholder:text-muted-fg">
{({ isPlaceholder, defaultChildren, selectedItems }) => {
if (isPlaceholder) {
return <span className="truncate">{defaultChildren}</span>;
}
// The items as they were passed in, or null for a key that is not in the list.
const chosen = (selectedItems as (ComboboxItem | null)[]).filter(
(item): item is ComboboxItem => item !== null,
);
if (chosen.length === 0) return null;
// Several picks: name them, or count them when there are many.
if (isMultiple && chosen.length > maxLabels) {
return <span className="truncate">{chosen.length} selected</span>;
}
return (
<span className="flex min-w-0 items-center gap-2">
{!isMultiple && chosen[0].avatar ? (
<Avatar {...chosen[0].avatar} size="xs" />
) : !isMultiple && chosen[0].icon ? (
<span className="text-muted-fg [&_svg]:size-4">
{chosen[0].icon}
</span>
) : null}
<span className="truncate">
{chosen.map((item) => item.label).join(", ")}
</span>
</span>
);
}}
</SelectValue>
<ChevronsUpDownIcon className="text-muted-fg" />
</Button>
{description ? (
<Text slot="description" className="text-sm text-muted-fg">
{description}
</Text>
) : null}
<FieldError className="text-sm text-danger">{errorMessage}</FieldError>
<Popover className="popover z-50 min-w-(--trigger-width) overflow-hidden rounded-xl border bg-card text-card-fg shadow-lg">
<Autocomplete filter={contains}>
<SearchField
autoFocus
aria-label={searchPlaceholder}
className="flex items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 text-muted-fg" />
<Input
placeholder={searchPlaceholder}
className="h-10 w-full bg-transparent text-sm outline-none placeholder:text-muted-fg [&::-webkit-search-cancel-button]:hidden"
/>
</SearchField>
<ListBox
items={items}
className="max-h-64 overflow-auto p-1 outline-none"
renderEmptyState={() => (
<p className="px-3 py-6 text-center text-sm text-muted-fg">
{emptyMessage}
</p>
)}
>
{(item) => (
<ListBoxItem
id={item.id}
textValue={item.label}
className="flex cursor-default items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none data-disabled:opacity-50 data-focused:bg-muted data-selected:font-medium"
>
{({ isSelected }) => (
<>
<span className="flex min-w-0 flex-1 items-center gap-2">
{item.avatar ? (
<Avatar {...item.avatar} />
) : item.icon ? (
<span className="shrink-0 text-muted-fg [&_svg]:size-4">
{item.icon}
</span>
) : null}
<span className="flex min-w-0 flex-col">
<Text slot="label" className="truncate">
{item.label}
</Text>
{item.description ? (
<Text
slot="description"
className="truncate text-xs text-muted-fg"
>
{item.description}
</Text>
) : null}
</span>
</span>
{isSelected ? (
<CheckIcon className="size-4 shrink-0" />
) : null}
</>
)}
</ListBoxItem>
)}
</ListBox>
</Autocomplete>
{isClearable ? <Footer isMultiple={isMultiple} /> : null}
</Popover>
</AriaSelect>
);
}It imports CheckIcon, ChevronsUpDownIcon and SearchIcon from @/components/icons. Add those icons, or swap them for your own.
3. Add the popover styles
In src/app/globals.css copy the popover-in keyframes and the .popover[data-entering] rule. Without them the list still works, it just appears without the small fade.
4. Use it
import { Combobox } from "@/components/ui/combobox/combobox";Anatomy
A button, and under it a list that has a search box at the top.
<Combobox
label="Assignee"
description="They are notified when you save."
placeholder="Choose a person"
items={people}
defaultValue="ana"
/>| Part | Rendered as | Notes |
|---|---|---|
| Label | label | Names the field. Clicking it focuses the button. |
| Button | Button | Looks like a Select: shows what is picked, or the placeholder, with a chevron at the end. Click it, or press Enter, Space or the down arrow, to open the list. |
| Search box | SearchField in a popover | At the top of the list, and focused when it opens. Typing narrows the options. |
| List | ListBox | Every option that matches, with a check mark on the ones already picked. Shows a message when nothing matches. |
| Footer | count and Clear button | Appears once something is picked. It counts the picks and removes them all. |
| Description / error | text under the field | Help text, replaced by the error message when the field is invalid. |
Without a label, give the field an aria-label so a screen reader can name it.
Items
The options are a plain array of objects.
const people = [
{
id: "ana",
label: "Ana Wijaya",
description: "ana@example.com",
avatar: { src: "/avatars/ana.png", name: "Ana Wijaya" },
},
{ id: "budi", label: "Budi Santoso", isDisabled: true },
];| Field | Type | Notes |
|---|---|---|
| id | string | What goes in the value. Unique. |
| label | string | The text of the option and of the button. What searching matches. |
| description | ReactNode | A smaller line under the label in the list. |
| icon | ReactNode | An icon before the label, in the list and in the button (single pick). |
| avatar | AvatarProps | An avatar before the label, in the list and in the button (single pick). |
| isDisabled | boolean | Shown, but it cannot be picked. |
Examples
Click the button, type in the search box to narrow the list, and pick an option.
Usage
Label
Every field needs a name. Use label, or aria-label when the label is written elsewhere.
Description
Help text under the field.
With avatar
An option with an avatar shows it in the list and in the button. Its description is a second line in the list only. One option is disabled here.
With icon
An icon works the same way as an avatar.
Option descriptions
A second line under each option helps the user tell similar ones apart. The button shows only the label.
Multiple
Set selectionMode="multiple" to pick several. The list stays open while you pick. The button names up to two picks and counts more than that.
Named picks
maxLabels sets how many picks the button names before it falls back to the count.
Maximum picks
maxSelected stops more from being picked. The other options are disabled until one is unpicked, but the ones already picked stay clickable.
Uncontrolled
Let the field keep its own pick. Start with defaultValue, and give it a name to read it from a form.
Controlled
Keep the pick in your own state with value and onChange, so you can read, replace or clear it from outside. Nothing picked is null.
value: "next"
Controlled, multiple
With several picks the value is an array of ids.
value: [docs, design]
In a form
With a name, the pick is submitted with the form, holding its id. Several picks are several entries.
Sizes
Variants
Disabled
Validation
Set isInvalid with an errorMessage. The button gets a red border and the message shows under it.
Component API
Combobox takes the props below.
| Prop | Type | Default |
|---|---|---|
| items | ComboboxItem[] | - (required) |
| selectionMode | "single" | "multiple" | "single" |
| label | ReactNode | - |
| description | ReactNode | - |
| errorMessage | string | ((validation) => string) | - |
| placeholder | string | - |
| value | string | null (single), string[] (multiple) | - |
| defaultValue | string | null (single), string[] (multiple) | - |
| onChange | (value: string | null | string[]) => void | - |
| maxLabels | number | 2 |
| maxSelected | number | - |
| isClearable | boolean | true |
| searchPlaceholder | string | "Search…" |
| emptyMessage | string | "No results found." |
| name | string | - |
| variant | "outline" | "secondary" | "ghost" | "outline" |
| size | Button size | "md" |
| autoFocus | boolean | false |
| isDisabled | boolean | false |
| isInvalid | boolean | false |
| isRequired | boolean | false |
| aria-label | string | - (when there is no label) |