Menu

Components

Select

Pick one option from a list. Built on react-aria-components, with a Button as the trigger.

Introduction

Select is for choosing one option out of a handful to a few dozen. It shows the chosen option in a field, and opens a list under it to change it. The trigger is a Button, so it looks like the rest of the library and shares its variants and sizes.

  • Keyboard navigation, typeahead and screen reader support come from react-aria-components.
  • A label, help text, and an error message that appears when the field is invalid.
  • Static options, sections, a second line per option, or a dynamic list from data.
  • Search to filter long lists, multiple selection, and icons or avatars next to each option.
  • Works in a form: give it a name and the value is submitted with it.

Installation

centerUI has no CLI or registry yet: components are copied into your project. Select uses Button as its trigger, 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 clsx

Add Button first (see its Manual installation), then follow the steps below.

Manual installation

Copy this file into your project and keep the path, or adjust the imports.

1. Add the Select file

src/components/ui/select/select.tsxShow code
"use client";

import type { ReactNode } from "react";
import {
  Select as AriaSelect,
  type SelectProps as AriaSelectProps,
  Autocomplete,
  FieldError,
  Header,
  Input,
  Label,
  ListBox,
  ListBoxItem,
  type ListBoxItemProps,
  ListBoxSection,
  Popover,
  SearchField,
  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";
import { cx } from "@/lib/primitive";

type SelectionMode = "single" | "multiple";
type TriggerVariant = "outline" | "secondary" | "ghost";
type TriggerSize = NonNullable<React.ComponentProps<typeof Button>["size"]>;

export interface SelectProps<
  T extends object,
  M extends SelectionMode = "single",
> extends Omit<AriaSelectProps<T, M>, "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 trigger button. */
  variant?: TriggerVariant;
  /** Size of the trigger button. */
  size?: TriggerSize;
  /** Add a search box above the list that filters the options as you type. */
  isSearchable?: boolean;
  /** Placeholder of the search box. */
  searchPlaceholder?: string;
  /** Shown when the search matches nothing. */
  emptyMessage?: string;
  /** Items for a dynamic list. Pair it with a render function as `children`. */
  items?: Iterable<T>;
  className?: string;
  children: ReactNode | ((item: T) => ReactNode);
}

/**
 * A field that shows the chosen option and opens a list to pick another. The
 * trigger is a Button, so it shares its variants and sizes. Built on
 * react-aria's Select: keyboard navigation, typeahead, form submission (`name`)
 * and validation come from there.
 *
 * Set `selectionMode="multiple"` to pick several options, and `isSearchable`
 * to filter a long list by typing.
 *
 * @example
 * <Select label="Country" placeholder="Choose a country">
 *   <SelectItem id="id">Indonesia</SelectItem>
 *   <SelectItem id="sg">Singapore</SelectItem>
 * </Select>
 */
export function Select<T extends object, M extends SelectionMode = "single">({
  label,
  description,
  errorMessage,
  variant = "outline",
  size,
  isSearchable = false,
  searchPlaceholder = "Search…",
  emptyMessage = "No results found.",
  items,
  className,
  children,
  ...props
}: SelectProps<T, M>) {
  const { contains } = useFilter({ sensitivity: "base" });
  const isMultiple = props.selectionMode === "multiple";

  const list = (
    <ListBox
      items={items}
      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>
  );

  return (
    <AriaSelect
      {...props}
      className={cn("group/select flex w-full flex-col gap-1.5", className)}
    >
      {label ? (
        <Label className="text-sm font-medium group-data-required/select:after:ml-0.5 group-data-required/select:after:text-danger group-data-required/select:after:content-['*']">
          {label}
        </Label>
      ) : null}
      <Button
        variant={variant}
        size={size}
        className="w-full justify-between text-left font-normal group-data-invalid/select:border-danger"
      >
        {/* The trigger reuses the selected option (icon, avatar and text) but
            not its description or its check mark. */}
        <SelectValue className="flex min-w-0 flex-1 items-center gap-2 data-placeholder:text-muted-fg [&_[data-slot=check]]:hidden [&_[slot=description]]:hidden">
          {({
            isPlaceholder,
            defaultChildren,
            selectedItems,
            selectedText,
          }) => {
            if (isPlaceholder) {
              return <span className="truncate">{defaultChildren}</span>;
            }
            if (isMultiple) {
              const count = selectedItems.length;
              return (
                <span className="truncate">
                  {count > 2 ? `${count} selected` : selectedText}
                </span>
              );
            }
            return defaultChildren;
          }}
        </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">
        {isSearchable ? (
          <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>
            {list}
          </Autocomplete>
        ) : (
          list
        )}
      </Popover>
    </AriaSelect>
  );
}

export interface SelectItemProps extends ListBoxItemProps {
  /** A second, smaller line under the label. */
  description?: ReactNode;
  /** An icon before the label. Also shown in the trigger when chosen. */
  icon?: ReactNode;
  /** An avatar before the label. Also shown in the trigger when chosen. */
  avatar?: AvatarProps;
}

/**
 * One option. `id` is the key that `selectedKey` and `onSelectionChange` use.
 * Give it a `textValue` when its children are not plain text, so searching and
 * typeahead have something to match.
 */
export function SelectItem({
  description,
  icon,
  avatar,
  className,
  children,
  textValue,
  ...props
}: SelectItemProps) {
  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 data-slot="check" className="size-4 shrink-0" />
          ) : null}
        </>
      )}
    </ListBoxItem>
  );
}

export interface SelectSectionProps {
  title: ReactNode;
  children: ReactNode;
}

/** A titled group of options, separated from the group above it. */
export function SelectSection({ title, children }: SelectSectionProps) {
  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 SearchIcon from @/components/icons. Add those icons, or swap them for your own.

2. Add the Avatar file

Select 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>
  );
}

3. 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.

4. Use it

import {
  Select,
  SelectItem,
  SelectSection,
} from "@/components/ui/select/select";

Anatomy

A select is a field with a trigger and a list.

<Select label="Country" description="Where you live" placeholder="Choose">
  <SelectSection title="Asia">
    <SelectItem id="id" description="Jakarta">Indonesia</SelectItem>
    <SelectItem id="sg">Singapore</SelectItem>
  </SelectSection>
</Select>
PartRendered asNotes
LabellabelNames the field. Clicking it focuses the trigger.
TriggerButtonShows the chosen option and opens the list. It shares the Button variants and sizes.
Valuespan in the triggerThe chosen option's text, or the placeholder.
Description / errortext under the triggerHelp text, replaced by the error message when the field is invalid.
Popoverfloating panelHolds the list. At least as wide as the trigger.
ItemoptionOne choice, with an optional second line. The chosen one shows a check.
Sectiongroup of optionsAn 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

Country

Label

Every field needs a name. Use label, or aria-label when the label is written elsewhere.

Country
Country

Description

Help text under the field. Here an option is already chosen with defaultSelectedKey.

TimezoneUsed for scheduling and reminders.

Item descriptions

A second line under an option. The trigger shows only the label.

Plan

Searchable

Set isSearchable to show a search box in the list. Typing filters the options, and the box is focused when the list opens.

Country

With icon

Give an option an icon. It is shown in the list and in the trigger when the option is chosen.

Add to

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.

Assignee

Multiple

Set selectionMode="multiple" to choose several options. The list stays open while you pick, and the trigger shows the names, or a count when more than two are chosen. Use defaultValue for an uncontrolled field, or value with onChange to control it.

FrameworksPick as many as you like.
Reviewers

value: [ana, citra, dimas]

Sections

Group related options under a title.

Country

Dynamic items

Build the options from data: pass items and a render function.

Framework

Uncontrolled

Let the component keep its own state. Start with defaultSelectedKey and read the value from a form, using name, when you need it.

Framework

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.

Framework

selectedKey: remix

Sizes

Variants

Disabled

Disable the whole field, or single options with disabledKeys.

Disabled field
One disabled option

Validation

Set isInvalid with an errorMessage. The trigger gets a red border and the message replaces the description.

Plan

Component API

Select, SelectItem and SelectSection take the props below, plus everything the react-aria Select, ListBoxItem and ListBoxSection accept.

Select

PropTypeDefault
labelReactNode-
descriptionReactNode-
errorMessagestring | (validation) => string-
placeholderstring"Select an item"
selectionMode"single" | "multiple""single"
selectedKeyKey | null- (single)
defaultSelectedKeyKey- (single)
onSelectionChange(key: Key | null) => void- (single)
valueKey[]- (multiple)
defaultValueKey[]- (multiple)
onChange(keys: Key[]) => void- (multiple)
isSearchablebooleanfalse
searchPlaceholderstring"Search…"
emptyMessagestring"No results found."
itemsIterable<T>-
disabledKeysIterable<Key>-
namestring-
variant"outline" | "secondary" | "ghost""outline"
size"xxs" | "xs" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "4xl""md"
isDisabledbooleanfalse
isInvalidbooleanfalse
isRequiredbooleanfalse
aria-labelstring- (when there is no label)

SelectItem

PropTypeDefault
idKey-
descriptionReactNode-
iconReactNode-
avatar{ src?, name?, alt?, size?, shape? }-
textValuestringthe text children
isDisabledbooleanfalse
childrenReactNode-

SelectSection

PropTypeDefault
titleReactNode-
childrenSelectItem elements-