Skip to content

Select

Lets people pick one option, or several, from a list that opens from a button.

Site

Installation

pnpm dlx shadcn@latest add @silkware/select

To copy the component by hand, install its dependencies:

pnpm add react-aria-components cn lucide-react

Then copy the source into components/ui/select.tsx. It also needs Input Group, used by the searchable variant:

components/ui/select.tsx
"use client"
import * as React from "react"import { cn } from "cn"import {  Button as ButtonPrimitive,  composeRenderProps,  FieldErrorContext,  Header as HeaderPrimitive,  ListBoxItem as ListBoxItemPrimitive,  ListBox as ListBoxPrimitive,  ListBoxSection as ListBoxSectionPrimitive,  OverlayTriggerStateContext,  Popover as PopoverPrimitive,  SearchField,  Select as SelectPrimitive,  SelectStateContext,  SelectValue as SelectValuePrimitive,  Separator as SeparatorPrimitive,  type ListBoxProps,  type SearchFieldProps,  type ListBoxSectionProps as SelectGroupProps,  type SelectProps,  type SelectValueProps,} from "@animate-ui/react/primitives/react-aria"
import {  InputGroup,  InputGroupAddon,  InputGroupInput,} from "@/components/ui/input-group"import { ChevronDownIcon, SearchIcon, CheckIcon } from "lucide-react"
function Select<T extends object, M extends "single" | "multiple" = "single">({  className,  ...props}: SelectProps<T, M>) {  return (    <SelectPrimitive      data-slot="select"      className={cn("w-fit", className)}      {...props}    />  )}
function SelectGroup<T extends object>({  className,  ...props}: SelectGroupProps<T>) {  return (    <ListBoxSectionPrimitive      data-slot="select-group"      className={cn("scroll-my-1 p-1", className)}      {...props}    />  )}
function SelectValue<T extends object>({  className,  children,  ...props}: SelectValueProps<T>) {  return (    <SelectValuePrimitive      data-slot="select-value"      className={cn(        "flex flex-1 text-left data-placeholder:text-muted-foreground",        className      )}      {...props}    >      {typeof children === "function"        ? children        : ({ selectedItems, selectedText, defaultChildren }) =>            selectedItems.length > 1 ? selectedText : defaultChildren}    </SelectValuePrimitive>  )}
function SelectTrigger({  className,  size = "default",  children,  ...props}: Omit<React.ComponentProps<typeof ButtonPrimitive>, "children"> & {  children?: React.ReactNode  size?: "sm" | "default"}) {  const validation = React.useContext(FieldErrorContext)  return (    <ButtonPrimitive      data-slot="select-trigger"      data-size={size}      data-invalid={validation?.isInvalid || undefined}      className={cn(        "flex w-full items-center justify-between gap-1.5 rounded-md border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-invalid:border-destructive data-invalid:ring-3 data-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:data-invalid:border-destructive/50 dark:data-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",        className      )}      {...props}    >      {children}      <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />    </ButtonPrimitive>  )}
function SelectContent({  className,  children,  placement = "bottom",  offset = 4,  crossOffset = 0,  ...props}: Omit<  React.ComponentProps<typeof PopoverPrimitive>,  "className" | "children"> & {  className?: string  children?: React.ReactNode}) {  return (    <SelectPopover      className={className}      placement={placement}      offset={offset}      crossOffset={crossOffset}      {...props}    >      <SelectList>{children}</SelectList>    </SelectPopover>  )}
function SelectPopover({  className,  children,  placement = "bottom start",  offset = 4,  crossOffset = 0,  ...props}: Omit<  React.ComponentProps<typeof PopoverPrimitive>,  "className" | "children"> & {  className?: string  children?: React.ReactNode}) {  return (    <OverlayTriggerStateContext value={React.use(SelectStateContext)}>      <PopoverPrimitive        data-slot="select-content"        placement={placement}        offset={offset}        crossOffset={crossOffset}        className={cn(          "relative isolate z-50 w-(--trigger-width) min-w-36 origin-(--trigger-anchor-point) overflow-hidden rounded-md bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 **:data-[slot$=-item]:data-focused:bg-foreground/10",          className        )}        {...props}      >        {children}      </PopoverPrimitive>    </OverlayTriggerStateContext>  )}
function SelectList<T extends object>({  className,  ...props}: ListBoxProps<T>) {  return (    <ListBoxPrimitive      data-slot="select-list"      className={cn(        "group/select-list max-h-[inherit] overflow-x-hidden overflow-y-auto p-0 outline-hidden",        className      )}      {...props}    />  )}
function SelectInput({ className, ...props }: SearchFieldProps) {  return (    <SearchField      {...props}      autoFocus      data-slot="select-input-wrapper"      className={cn("p-1 pb-0", className)}    >      <InputGroup>        <InputGroupInput          data-slot="select-input"          className="[&::-webkit-search-cancel-button]:hidden"        />        <InputGroupAddon>          <SearchIcon className="size-4 shrink-0 opacity-50" />        </InputGroupAddon>      </InputGroup>    </SearchField>  )}
function SelectLabel({  className,  ...props}: React.ComponentProps<typeof HeaderPrimitive>) {  return (    <HeaderPrimitive      data-slot="select-label"      className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}      {...props}    />  )}
function SelectItem({  className,  children,  ...props}: React.ComponentProps<typeof ListBoxItemPrimitive>) {  return (    <ListBoxItemPrimitive      data-slot="select-item"      textValue={typeof children === "string" ? children : undefined}      className={cn(        "relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-focused:bg-accent data-focused:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",        className      )}      {...props}    >      {composeRenderProps(children, (children, { isSelected }) => (        <>          <span className="flex flex-1 shrink-0 gap-2 whitespace-nowrap">            {children}          </span>          <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">            {isSelected ? (              <CheckIcon className="pointer-events-none" />            ) : null}          </span>        </>      ))}    </ListBoxItemPrimitive>  )}
function SelectSeparator({  className,  ...props}: React.ComponentProps<typeof SeparatorPrimitive>) {  return (    <SeparatorPrimitive      data-slot="select-separator"      className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}      {...props}    />  )}
function SelectEmpty({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="select-empty"      className={cn(        "hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/select-list:flex",        className      )}      {...props}    />  )}
export {  Select,  SelectContent,  SelectGroup,  SelectInput,  SelectItem,  SelectLabel,  SelectList,  SelectPopover,  SelectSeparator,  SelectTrigger,  SelectValue,  SelectEmpty,}

Usage

import {  Select,  SelectContent,  SelectItem,  SelectTrigger,  SelectValue,} from "@/components/ui/select"import { Label } from "@/components/ui/label"
<Select placeholder="Choose a site">  <Label>Site</Label>  <SelectTrigger>    <SelectValue />  </SelectTrigger>  <SelectContent>    <SelectItem id="bergamo">Bergamo plant</SelectItem>    <SelectItem id="verona">Verona warehouse</SelectItem>  </SelectContent></Select>

Every item needs an id. The id is the value that value, defaultValue and onChange work with; the children are only the label shown to people. The Label goes inside Select so React Aria can connect it to the button and the list. A label placed outside the Select is not connected to it.

Select is w-fit by default. Give it a width, or make it a column with className="flex w-full max-w-64 flex-col gap-2" when the label sits above the button.

Examples

Groups

Split a long list into named groups with SelectGroup and SelectLabel, and separate them with SelectSeparator. Use groups when people think in categories, such as plants and warehouses.

Delivery site

Size

SelectTrigger takes size="sm" for dense toolbars and table filters. The default height matches the other form controls.

With description

Put help text under the button when the choice has a consequence the label does not carry.

Approver

Orders above 5,000 EUR need approval.

Disabled

isDisabled on Select disables the whole control. isDisabled on one SelectItem keeps the option visible but not selectable. Explain nearby why an option is unavailable.

Whole select disabled
One option disabled

Invalid

Set isInvalid on Select, or let validation set it, and the trigger shows the error border. Put the reason in a React Aria FieldError inside the Select, so it is announced with the trigger. Say what to do, not only that something is wrong.

Delivery site

Multiple selection

Set selectionMode="multiple" to let people pick several options. value and onChange then use an array of ids, and the button shows the single choice by name or a joined text once several are picked. The list stays open between choices.

Notify departments

Controlled

Use value and onChange when something else on the page depends on the choice. Use defaultValue when only the form submission matters.

Supplier

Selected id: ferrolva

Searchable

For a long list, wrap SelectPopover in React Aria's Autocomplete and add SelectInput and SelectList. The input filters the options as people type, and renderEmptyState shows SelectEmpty when nothing matches. This is the right shape for a list of 10 to 50 options. For hundreds, or when people type free text, use a Combobox.

Supplier

Accessibility

KeyAction
SpaceOpens the list, or selects the focused option when the list is open.
EnterOpens the list, or selects the focused option when the list is open.
ArrowDownOpens the list when it is closed, and moves focus to the next option when it is open.
ArrowUpOpens the list when it is closed, and moves focus to the previous option when it is open.
ArrowLeftOn the closed button, selects the previous option without opening the list. Single selection only.
ArrowRightOn the closed button, selects the next option without opening the list. Single selection only.
HomeMoves focus to the first option.
EndMoves focus to the last option.
EscapeCloses the list and returns focus to the button.
TabCloses the list and moves focus to the next control.

Typing a few letters while the button is focused or the list is open moves to the option that starts with them.

React Aria provides:

  • A button with aria-haspopup="listbox" and aria-expanded, and a list with the listbox role and option items that report their selected and disabled state.
  • Focus that moves into the list when it opens and returns to the button when it closes.
  • Typeahead, and a hidden native <select> so the value takes part in form submission and browser autofill.
  • Labelling: the Label inside Select names both the button and the list.

You provide:

  • A visible Label, or an aria-label when the context already names the field.
  • A placeholder that describes the action ("Choose a site"). It disappears once a value is chosen, so it never replaces the label.
  • Text on every item that tells the options apart without relying on colour or position.
  • An error message in FieldError together with isInvalid.

Guidelines

When to use

  • To choose one value from a closed list of about 5 to 15 options: a site, a supplier, an order status.
  • To choose several values from a short closed list, with selectionMode="multiple".
  • When space is tight and showing every option would crowd the form.

When not to use

  • For two to four options that people should compare at a glance. Use a Radio Group, or Tabs when the choice switches a view.
  • For a yes or no. Use a Switch or a Checkbox.
  • For a long list, or when people can type a value that is not in the list. Use a Combobox.
  • When the browser's own picker is better, such as on a phone or in a plain form. Use a Native Select.
  • For a list of actions. Use a Dropdown Menu.

Content

  • Label the field with a noun, in sentence case: "Delivery site", not "Select a delivery site".
  • Start the placeholder with a verb: "Choose a site".
  • Write options as short noun phrases. Put the most common option first, or sort alphabetically when people look for a known name.
  • Do not add a "None" or "Select" option to the list. Let people clear a value in another way, or leave the field optional.

Label and placeholder

A placeholder is not a label. It vanishes when a value is chosen, and people lose the name of the field.

Delivery site
Do

Show a visible label above the select and use the placeholder for the action.

Don’t

Don’t use the placeholder as the only label. After the choice, nothing says what the field is.

Carrier
Do

Use a select when the list is long enough that showing every option would crowd the form.

Priority
Don’t

Don’t hide two options behind a click. A radio group shows both and saves a press.

API reference

Select

The root. It renders a <div> through the React Aria Select and accepts every prop of it, including children, items and disabledKeys. It sets w-fit and merges your className after it.

PropTypeDefaultDescription
selectionMode?"single" | "multiple""single"Whether people can choose one option or several.
value?Key | Key[] | nullNoneThe selected id, or ids with multiple selection. Use with onChange for a controlled select.
defaultValue?Key | Key[] | nullNoneThe initial selection of an uncontrolled select.
onChange?(value: Key | Key[] | null) => voidNoneCalled when the selection changes.
placeholder?stringNoneText shown on the button while nothing is selected.
isDisabled?booleanfalseDisables the button and the list.
isInvalid?booleanfalseMarks the select as invalid.
isRequired?booleanfalseRequires a choice before a form can be submitted.
name?stringNoneThe name used when the select is submitted with a form.
disabledKeys?Iterable<Key>NoneIds of options that cannot be selected.
aria-label?stringNoneA label for the select when there is no visible Label.
className?stringNoneClasses merged after w-fit.

SelectTrigger

The button that shows the current value and opens the list. It renders the React Aria Button with a chevron after its children.

PropTypeDefaultDescription
size?"sm" | "default""default"The height of the button: 32px for sm, 36px for default.
className?stringNoneClasses merged after the base classes. Set the width here.

SelectValue

The text inside the trigger. It shows the placeholder, the selected option, or the joined text when several are selected. It accepts the props of the React Aria SelectValue, including a render function for custom output.

SelectContent

The popover with the list inside. It renders a Popover and a SelectList, and accepts the props of the React Aria Popover apart from children and className.

PropTypeDefaultDescription
placement?Placement"bottom"Where the list opens relative to the button.
offset?number4The distance from the button, in pixels.
crossOffset?number0The offset along the other axis, in pixels.
className?stringNoneClasses merged onto the popover.

SelectItem

One option. It renders a React Aria ListBoxItem and shows a check mark when it is selected. A string child also becomes its textValue; pass textValue yourself when the children are not a plain string.

PropTypeDefaultDescription
id?KeyNoneThe value of the option. It is what value and onChange use, so set it on every option.
isDisabled?booleanfalseKeeps the option visible but not selectable.
textValue?stringNonePlain text used for typeahead and for the button when the children are not a string.

SelectGroup, SelectLabel and SelectSeparator

SelectGroup renders a React Aria ListBoxSection. SelectLabel is the heading of a group. SelectSeparator draws a line between groups. Give SelectGroup an items array and a render function to build a group from data.

SelectPopover, SelectList, SelectInput and SelectEmpty

The parts SelectContent is made of, exported so you can compose a searchable select. SelectPopover is the popover, SelectList is the React Aria ListBox, SelectInput is a SearchField with a search icon that takes focus when the list opens, and SelectEmpty is the message shown by the list's renderEmptyState when a search finds nothing. Wrap SelectPopover in React Aria's Autocomplete to filter the options.