Components
Autocomplete
A text field with suggestions. Type to narrow a long list, then pick an option. Built on react-aria-components.
Introduction
Autocomplete is a text field that suggests options as you type. Reach for it instead of Select when the list is long enough that scrolling to find an option is slow, or when the user may also want to write a value of their own.
- The list opens on focus and narrows as you type. Keyboard navigation and screen reader support come from react-aria.
- A clear button, a label, help text, and an error message that shows when the field is invalid.
- Static options, sections, a second line, an icon or an avatar per option, or a dynamic list from data.
- Filter for you, or bring your own filtering (for example from a server), and optionally accept text that is not in the list.
Installation
centerUI has no CLI or registry yet: components are copied into your project. Autocomplete uses Button, so it needs everything Button needs.
# 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 styles
src/types/autocomplete-styles.tsShow code
import { tv } from "tailwind-variants";
// The frame around the input and its buttons. It is a plain element, not the
// input itself, so the buttons sit inside the same border and the focus ring
// wraps all of them.
export const autocompleteFieldStyles = tv({
base: [
"flex w-full items-center gap-1 rounded-md text-fg transition-colors",
"focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-bg",
"group-data-invalid/autocomplete:border-danger",
"group-data-disabled/autocomplete:pointer-events-none group-data-disabled/autocomplete:opacity-50",
],
variants: {
variant: {
outline: "border bg-transparent",
secondary: "bg-secondary text-secondary-fg",
ghost: "bg-transparent hover:bg-muted focus-within:bg-muted",
},
size: {
sm: "h-8 pr-1 pl-3 text-sm",
md: "h-9 pr-1 pl-3 text-sm",
lg: "h-11 pr-1.5 pl-4 text-base",
},
},
defaultVariants: { variant: "outline", size: "md" },
});2. Add the Autocomplete file
src/components/ui/autocomplete/autocomplete.tsxShow code
"use client";
import { type ReactNode, useContext } from "react";
import {
ComboBox,
type ComboBoxProps,
ComboBoxStateContext,
FieldError,
Group,
Header,
Input,
Label,
ListBox,
ListBoxItem,
type ListBoxItemProps,
ListBoxSection,
Popover,
Text,
type ValidationResult,
} from "react-aria-components";
import { CheckIcon, ChevronsUpDownIcon, XIcon } from "@/components/icons";
import { Avatar, type AvatarProps } from "@/components/ui/avatar/avatar";
import { Button } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import { cx } from "@/lib/primitive";
import { autocompleteFieldStyles } from "@/types/autocomplete-styles";
type FieldSize = "sm" | "md" | "lg";
export interface AutocompleteProps<T extends object>
extends Omit<ComboBoxProps<T>, "children" | "className"> {
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);
/** Look of the field. */
variant?: "outline" | "secondary" | "ghost";
/** Size of the field. */
size?: FieldSize;
placeholder?: string;
/** Show a button that clears the text and the selection. Defaults to `true`. */
isClearable?: boolean;
/** Shown when nothing matches what was typed. */
emptyMessage?: string;
className?: string;
children: ReactNode | ((item: T) => ReactNode);
}
const buttonSize = { sm: "xs", md: "xs", lg: "sm" } as const;
// Needs the combo box state, so it lives inside the ComboBox. It is hidden
// while there is nothing to clear.
function ClearButton({ size }: { size: FieldSize }) {
const state = useContext(ComboBoxStateContext);
if (!state || state.inputValue === "") return null;
return (
<Button
// `slot={null}` keeps react-aria from wiring this up as the open/close
// button.
slot={null}
isIcon
variant="ghost"
size={buttonSize[size]}
aria-label="Clear"
onPress={() => {
state.setSelectedKey(null);
state.setInputValue("");
}}
>
<XIcon />
</Button>
);
}
/**
* A text field with a list of suggestions. Type to narrow the list, then pick
* an option. Unlike Select the user can type, so it suits long lists. Built on
* react-aria's ComboBox: keyboard navigation, screen reader support, form
* submission (`name`) and validation come from there.
*
* Pass `defaultItems` with a render function to let it filter for you. Pass
* `items` (and `inputValue`/`onInputChange`) to filter yourself, for example
* from a server.
*
* @example
* <Autocomplete label="Country" placeholder="Search a country">
* <AutocompleteItem id="id">Indonesia</AutocompleteItem>
* <AutocompleteItem id="sg">Singapore</AutocompleteItem>
* </Autocomplete>
*/
export function Autocomplete<T extends object>({
label,
description,
errorMessage,
variant,
size = "md",
placeholder,
isClearable = true,
emptyMessage = "No results found.",
className,
children,
...props
}: AutocompleteProps<T>) {
return (
<ComboBox
menuTrigger="focus"
// Keep the list open with the empty message instead of closing it when
// nothing matches.
allowsEmptyCollection
{...props}
className={cn(
"group/autocomplete flex w-full flex-col gap-1.5",
className,
)}
>
{label ? (
<Label className="text-sm font-medium group-data-required/autocomplete:after:ml-0.5 group-data-required/autocomplete:after:text-danger group-data-required/autocomplete:after:content-['*']">
{label}
</Label>
) : null}
<Group className={autocompleteFieldStyles({ variant, size })}>
<Input
placeholder={placeholder}
className="h-full min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-fg"
/>
{isClearable ? <ClearButton size={size} /> : null}
<Button isIcon variant="ghost" size={buttonSize[size]}>
<ChevronsUpDownIcon className="text-muted-fg" />
</Button>
</Group>
{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">
<ListBox
className="max-h-72 overflow-auto p-1 outline-none"
renderEmptyState={() => (
<p className="px-3 py-6 text-center text-sm text-muted-fg">
{emptyMessage}
</p>
)}
>
{children}
</ListBox>
</Popover>
</ComboBox>
);
}
export interface AutocompleteItemProps extends ListBoxItemProps {
/** A second, smaller line under the label. */
description?: ReactNode;
/** An icon before the label. */
icon?: ReactNode;
/** An avatar before the label. */
avatar?: AvatarProps;
}
/**
* One suggestion. `id` is the key that `selectedKey` and `onSelectionChange`
* use. The text typed into the field is matched against `textValue`, which is
* taken from the children when they are plain text.
*/
export function AutocompleteItem({
description,
icon,
avatar,
className,
children,
textValue,
...props
}: AutocompleteItemProps) {
return (
<ListBoxItem
{...props}
textValue={
textValue ?? (typeof children === "string" ? children : undefined)
}
className={cx(
"flex cursor-default items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none",
"data-focused:bg-muted data-selected:font-medium data-disabled:opacity-50",
className,
)}
>
{(renderProps) => (
<>
<span className="flex min-w-0 flex-1 items-center gap-2">
{avatar ? (
<Avatar {...avatar} />
) : icon ? (
<span className="shrink-0 text-muted-fg [&_svg]:size-4">
{icon}
</span>
) : null}
<span className="flex min-w-0 flex-col">
<Text slot="label" className="truncate">
{typeof children === "function"
? children(renderProps)
: children}
</Text>
{description ? (
<Text
slot="description"
className="truncate text-xs text-muted-fg"
>
{description}
</Text>
) : null}
</span>
</span>
{renderProps.isSelected ? (
<CheckIcon className="size-4 shrink-0" />
) : null}
</>
)}
</ListBoxItem>
);
}
export interface AutocompleteSectionProps {
title: ReactNode;
children: ReactNode;
}
/** A titled group of suggestions, separated from the group above it. */
export function AutocompleteSection({
title,
children,
}: AutocompleteSectionProps) {
return (
<ListBoxSection className="not-first:mt-1 not-first:border-t not-first:pt-1">
<Header className="px-2.5 py-1.5 text-xs font-medium text-muted-fg">
{title}
</Header>
{children}
</ListBoxSection>
);
}It imports CheckIcon, ChevronsUpDownIcon and XIcon from @/components/icons. Add those icons, or swap them for your own.
3. Add the Avatar file
Autocomplete imports Avatar for the avatar prop. Skip this step and remove that 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>
);
}4. Add the popover styles
In src/app/globals.css copy the popover-in keyframes and the .popover[data-entering] rule (with its prefers-reduced-motion override). Without them the list still works, it just appears without the small fade.
5. Use it
import {
Autocomplete,
AutocompleteItem,
AutocompleteSection,
} from "@/components/ui/autocomplete/autocomplete";Anatomy
An autocomplete is a field with an input, two buttons and a list.
<Autocomplete label="Country" description="Where you live" placeholder="Search">
<AutocompleteSection title="Asia">
<AutocompleteItem id="id" description="Jakarta">Indonesia</AutocompleteItem>
<AutocompleteItem id="sg">Singapore</AutocompleteItem>
</AutocompleteSection>
</Autocomplete>| Part | Rendered as | Notes |
|---|---|---|
| Label | label | Names the field. Clicking it focuses the input. |
| Input | input | Where the user types. It shows the chosen option's text. |
| Clear button | Button | Empties the input and the selection. Shown only when there is text. |
| Toggle button | Button | Opens and closes the list. |
| Description / error | text under the field | Help text, replaced by the error message when the field is invalid. |
| Popover | floating panel | Holds the suggestions. At least as wide as the field. |
| Item | option | One suggestion, with an optional second line, icon or avatar. |
| Section | group of options | An optional title above a group of items. |
Without a label, give the field an aria-label so a screen reader can name it.
Examples
Live previews with code you can copy.
Usage
Label
Every field needs a name. Use label, or aria-label when the label is written elsewhere.
Description
Help text under the field.
Item descriptions
A second line under an option. Only the label is put in the input when it is chosen.
With icon
Give an option an icon that is shown in the list.
With avatar
Pass avatar props to show a picture. If the image is missing or fails to load, the initials of name are shown. Set textValue when the label is not plain text.
Sections
Group related options under a title.
Dynamic items
Build the options from data: pass defaultItems and a render function.
Uncontrolled
Let the component keep its own state. Start with defaultSelectedKey, and give it a name to read the value from a form.
Controlled
Keep the chosen option in your own state with selectedKey and onSelectionChange, so you can read it, set it or clear it from outside.
selectedKey: remix
Custom filtering
Control the typed text with inputValue and onInputChange, and pass the already filtered list as items. Here only names that start with the text match.
8 of 8 match “”
Custom value
Set allowsCustomValue to keep text that is not in the list, instead of resetting the input when it loses focus.
inputValue: “”
Sizes
Variants
Disabled
Disable the whole field, or single options with disabledKeys.
Validation
Set isInvalid with an errorMessage. The field gets a red border and the message replaces the description.
Component API
Autocomplete, AutocompleteItem and AutocompleteSection take the props below, plus everything the react-aria ComboBox, ListBoxItem and ListBoxSection accept.
Autocomplete
| Prop | Type | Default |
|---|---|---|
| label | ReactNode | - |
| description | ReactNode | - |
| errorMessage | string | (validation) => string | - |
| placeholder | string | - |
| defaultItems | Iterable<T> | - (filtered for you) |
| items | Iterable<T> | - (you filter) |
| selectedKey | Key | null | - |
| defaultSelectedKey | Key | - |
| onSelectionChange | (key: Key | null) => void | - |
| inputValue | string | - |
| defaultInputValue | string | - |
| onInputChange | (value: string) => void | - |
| allowsCustomValue | boolean | false |
| menuTrigger | "focus" | "input" | "manual" | "focus" |
| isClearable | boolean | true |
| emptyMessage | string | "No results found." |
| disabledKeys | Iterable<Key> | - |
| name | string | - |
| variant | "outline" | "secondary" | "ghost" | "outline" |
| size | "sm" | "md" | "lg" | "md" |
| isDisabled | boolean | false |
| isInvalid | boolean | false |
| isRequired | boolean | false |
| aria-label | string | - (when there is no label) |
Use defaultItems and the component filters them by what is typed (case-insensitive, matching anywhere in the text). Use items and you decide what is shown, which is what you want for server-side search.
AutocompleteItem
| Prop | Type | Default |
|---|---|---|
| id | Key | - |
| description | ReactNode | - |
| icon | ReactNode | - |
| avatar | { src?, name?, alt?, size?, shape? } | - |
| textValue | string | the text children |
| isDisabled | boolean | false |
| children | ReactNode | - |
AutocompleteSection
| Prop | Type | Default |
|---|---|---|
| title | ReactNode | - |
| children | AutocompleteItem elements | - |