Skip to content

Combobox

Combines a text input with a filtered list, so people can search a long list and pick from it.

Installation

pnpm dlx shadcn@latest add @silkware/combobox

To copy the component by hand, install its dependencies:

pnpm add react-aria-components cn lucide-react

Then copy the source into components/ui/combobox.tsx. It also needs Button and Input Group:

components/ui/combobox.tsx
"use client"
import * as React from "react"import { cn } from "cn"import {  Button as ButtonPrimitive,  Collection,  ComboBox as ComboBoxPrimitive,  ComboBoxStateContext,  ComboBoxValue as ComboBoxValuePrimitive,  composeRenderProps,  Group,  Header as HeaderPrimitive,  Input as InputPrimitive,  ListBoxItem as ListBoxItemPrimitive,  ListBox as ListBoxPrimitive,  ListBoxSection as ListBoxSectionPrimitive,  OverlayTriggerStateContext,  Popover as PopoverPrimitive,  Separator as SeparatorPrimitive,  TagGroup as TagGroupPrimitive,  TagList as TagListPrimitive,  Tag as TagPrimitive,  type ButtonProps,  type ComboBoxValueProps,  type GroupProps,  type HeaderProps,  type InputProps,  type ListBoxItemProps,  type ListBoxProps,  type ListBoxSectionProps,  type SeparatorProps,  type TagListProps,  type TagProps,} from "@animate-ui/react/primitives/react-aria"
import { Button } from "@/components/ui/button"import {  InputGroup,  InputGroupAddon,  InputGroupButton,  InputGroupInput,} from "@/components/ui/input-group"import { ChevronDownIcon, XIcon, CheckIcon } from "lucide-react"
function ComboboxValue<T>({ ...props }: ComboBoxValueProps<T>) {  return <ComboBoxValuePrimitive data-slot="combobox-value" {...props} />}
function ComboboxTrigger({  className,  children,  ...props}: Omit<ButtonProps, "children"> & {  children?: React.ReactNode}) {  return (    <ButtonPrimitive      data-slot="combobox-trigger"      className={cn("[&_svg:not([class*='size-'])]:size-4", className)}      {...props}    >      {children}      <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />    </ButtonPrimitive>  )}
function ComboboxClear({  className,  ...props}: React.ComponentProps<typeof InputGroupButton>) {  const state = React.useContext(ComboBoxStateContext)  if (state?.inputValue === "") {    return null  }
  return (    <InputGroupButton      data-slot="combobox-clear"      variant="ghost"      size="icon-xs"      aria-label="Clear"      className={cn(className)}      onPress={() => {        state?.setValue(null)      }}      slot={null}      {...props}    >      <XIcon className="pointer-events-none" />    </InputGroupButton>  )}
function ComboboxInput({  className,  children,  disabled = false,  showTrigger = true,  showClear = false,  ...props}: React.ComponentProps<"input"> & {  showTrigger?: boolean  showClear?: boolean}) {  return (    <InputGroup className={cn("w-auto", className)}>      <InputGroupInput disabled={disabled} {...props} />      <InputGroupAddon align="inline-end">        {showTrigger && (          <InputGroupButton            size="icon-xs"            variant="ghost"            data-slot="combobox-trigger"            className="group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent [&_svg:not([class*='size-'])]:size-4"            isDisabled={disabled}          >            <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />          </InputGroupButton>        )}        {showClear && <ComboboxClear isDisabled={disabled} />}      </InputGroupAddon>      {children}    </InputGroup>  )}
function ComboboxContent({  className,  placement = "bottom",  offset = 6,  crossOffset = 0,  anchor,  ...props}: Omit<  React.ComponentProps<typeof PopoverPrimitive>,  "className" | "children"> & {  className?: string  children?: React.ReactNode  anchor?: React.RefObject<HTMLDivElement | null>}) {  return (    <OverlayTriggerStateContext value={React.use(ComboBoxStateContext)}>      <PopoverPrimitive        data-slot="combobox-content"        placement={placement}        offset={offset}        crossOffset={crossOffset}        triggerRef={anchor}        className={cn(          "relative isolate z-50 max-h-72 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 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none",          className        )}        {...props}      />    </OverlayTriggerStateContext>  )}
function ComboboxList<T extends object>({  className,  ...props}: ListBoxProps<T>) {  return (    <ListBoxPrimitive      data-slot="combobox-list"      className={cn(        "group/combobox-content no-scrollbar max-h-[inherit] scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",        className      )}      {...props}    />  )}
function ComboboxItem<T extends object>({  className,  children,  ...props}: ListBoxItemProps<T>) {  return (    <ListBoxItemPrimitive      data-slot="combobox-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 data-focused:bg-accent data-focused:text-accent-foreground not-data-[variant=destructive]:data-focused:**:text-accent-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**: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",        className      )}      {...props}    >      {composeRenderProps(children, (children, { isSelected }) => (        <>          {children}          <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 ComboboxGroup<T extends object>({  className,  ...props}: ListBoxSectionProps<T>) {  return (    <ListBoxSectionPrimitive      data-slot="combobox-group"      className={cn(className)}      {...props}    />  )}
function ComboboxLabel({ className, ...props }: HeaderProps) {  return (    <HeaderPrimitive      data-slot="combobox-label"      className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}      {...props}    />  )}
function ComboboxEmpty({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="combobox-empty"      className={cn(        "hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex",        className      )}      {...props}    />  )}
function ComboboxSeparator({ className, ...props }: SeparatorProps) {  return (    <SeparatorPrimitive      data-slot="combobox-separator"      className={cn("-mx-1 my-1 h-px bg-border", className)}      {...props}    />  )}
function ComboboxChips({ children, className, ...props }: GroupProps) {  return (    <Group      data-slot="combobox-chips"      className={cn(        "flex min-h-9 flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 py-1.5 text-sm shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1.5 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40",        className      )}      {...props}    >      {children}    </Group>  )}
function ComboboxChipList<T extends object>({  className,  ...props}: Omit<TagListProps<T>, "className" | "items"> & {  className?: string}) {  return (    <ComboBoxValuePrimitive<T> className="contents">      {({ selectedItems, state }) => (        <TagGroupPrimitive          data-slot="combobox-chip-list"          className={cn("contents", className)}          onRemove={(keys) => {            if (Array.isArray(state.value)) {              state.setValue(state.value.filter((k) => !keys.has(k)))            }          }}        >          <TagListPrimitive            className="contents"            items={selectedItems.filter((item) => item != null)}            {...props}          />        </TagGroupPrimitive>      )}    </ComboBoxValuePrimitive>  )}
function ComboboxChip({  className,  children,  showRemove = true,  ...props}: Omit<TagProps, "children"> & {  showRemove?: boolean  children?: React.ReactNode}) {  return (    <TagPrimitive      data-slot="combobox-chip"      className={cn(        "flex h-[calc(--spacing(5.5))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-0",        className      )}      {...props}    >      {children}      {showRemove && (        <Button          slot="remove"          variant="ghost"          size="icon-xs"          className="-ml-1 opacity-50 hover:opacity-100"          data-slot="combobox-chip-remove"        >          <XIcon className="pointer-events-none" />        </Button>      )}    </TagPrimitive>  )}
function ComboboxChipsInput({ className, ...props }: InputProps) {  const state = React.useContext(ComboBoxStateContext)  return (    <InputPrimitive      data-slot="combobox-chip-input"      className={cn("min-w-16 flex-1 outline-none", className)}      onKeyDown={(e) => {        if (          e.key === "Backspace" &&          e.currentTarget.value === "" &&          Array.isArray(state?.value) &&          state.value.length > 0        ) {          e.preventDefault()          state.setValue(state.value.slice(0, -1))        }      }}      {...props}    />  )}
function useComboboxAnchor() {  return React.useRef<HTMLDivElement | null>(null)}
export {  ComboBoxPrimitive as Combobox,  ComboboxInput,  ComboboxContent,  ComboboxList,  ComboboxItem,  ComboboxGroup,  ComboboxLabel,  Collection as ComboboxCollection,  ComboboxEmpty,  ComboboxSeparator,  ComboboxChips,  ComboboxChip,  ComboboxChipList,  ComboboxChipsInput,  ComboboxTrigger,  ComboboxValue,  useComboboxAnchor,}

Usage

import {  Combobox,  ComboboxContent,  ComboboxEmpty,  ComboboxInput,  ComboboxItem,  ComboboxList,} from "@/components/ui/combobox"import { Label } from "@/components/ui/label"
<Combobox allowsEmptyCollection>  <Label>Supplier</Label>  <ComboboxInput placeholder="Search suppliers" />  <ComboboxContent>    <ComboboxList      renderEmptyState={() => <ComboboxEmpty>No supplier found.</ComboboxEmpty>}    >      <ComboboxItem id="ferrolva">Ferrolva Acciai</ComboboxItem>      <ComboboxItem id="imbaltra">Imbaltra</ComboboxItem>    </ComboboxList>  </ComboboxContent></Combobox>

Combobox is the React Aria ComboBox without styles, so give it a layout class yourself when the label sits above the input, for example className="flex w-full max-w-64 flex-col gap-2". Set allowsEmptyCollection whenever you render a ComboboxEmpty. Without it the list closes as soon as no option matches, and the empty message never shows.

Filtering is "contains" and ignores case by default. Items are matched on their text, so give an item a textValue when its children are not a plain string.

Examples

Groups

Wrap options in ComboboxGroup with a ComboboxLabel, and separate groups with ComboboxSeparator. Filtering applies inside every group, and groups with no match disappear.

Clear button

showClear on ComboboxInput adds a button that empties the field and the selection. It appears only while the input holds text, and it replaces the chevron.

With icon

Put an InputGroupAddon inside ComboboxInput to add an icon before the text. Shift the list with crossOffset so it still lines up with the input.

Multiple selection

Set selectionMode="multiple" and replace ComboboxInput with ComboboxChips: a ComboboxChipList that renders one ComboboxChip per selected item, followed by a ComboboxChipsInput. Backspace in an empty input removes the last chip, and each chip has its own remove button. Pass items on Combobox and a render function to ComboboxChipList and ComboboxList so chips can read the selected objects.

Giulia

Controlled

Use value and onChange to read the selected id. The value is the id of the item, not its text. Use inputValue and onInputChange to control the text typed in the field.

Selected id: none

Invalid

Set isInvalid on Combobox and aria-invalid on ComboboxInput so the field takes the error border, and explain the fix in a FieldError.

Disabled

isDisabled on Combobox and disabled on ComboboxInput turn the field off. Keep the current value visible so people can still read it.

Accessibility

KeyAction
ArrowDownOpens the list, or moves focus to the next option when it is open.
ArrowUpOpens the list, or moves focus to the previous option when it is open.
EnterSelects the focused option and closes the list.
EscapeCloses the list and puts back the text of the selected option, or empties the input when nothing is selected.
HomeMoves the text cursor to the start of the input.
EndMoves the text cursor to the end of the input.
TabSelects the focused option, closes the list and moves focus to the next control.
BackspaceIn the multiple selection input, removes the last chip when the input is empty.

React Aria provides:

  • The combobox role on the input, with aria-expanded, aria-controls and aria-activedescendant, so focus stays in the input while the list is navigated.
  • A listbox popup with option items, and screen reader announcements of how many options match and which one is focused.
  • Labelling: the Label inside Combobox names the input and the list.
  • Form submission of the selected id through a hidden input.

You provide:

  • A visible Label, or an aria-label on Combobox.
  • A renderEmptyState that explains that nothing matches, together with allowsEmptyCollection.
  • An aria-label on the chip remove buttons when the visible text is not enough in your language.
  • Option text that is meaningful out of context, because it is read alone by screen readers.

Guidelines

When to use

  • To pick one value from a long list that people can search: a supplier among 200, a part number, a customer.
  • To pick several values from a long list, shown as chips.
  • When people usually know part of the name they are looking for.

When not to use

  • For a short closed list of about 15 options or fewer. Use a Select.
  • For a list that should open the browser's own picker, especially on a phone. Use a Native Select.
  • For two to four options. Use a Radio Group.
  • To run commands or jump to pages from a keyboard shortcut. Use a Command.
  • For free text that only has suggestions. Use an Input and treat the suggestions as help.

Content

  • Label the field with a noun: "Supplier", not "Search for a supplier".
  • Write the placeholder as an invitation to type: "Search suppliers".
  • Make the empty message say what was searched and what to do: "No supplier found."
  • Put the text people search by first in each option, for example the supplier name before its code.

Empty state

Do

Set allowsEmptyCollection and show a message when nothing matches.

Don’t

Don’t leave the empty case out. The list closes when nothing matches and people cannot tell why.

API reference

Combobox

The root. It is the React Aria ComboBox exported under the name Combobox, with no extra styles, and accepts every prop of 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 field.
defaultValue?Key | Key[] | nullNoneThe initial selection of an uncontrolled field.
onChange?(value: Key | Key[] | null) => voidNoneCalled when the selection changes.
inputValue?stringNoneThe text in the input, for a controlled field.
onInputChange?(value: string) => voidNoneCalled when the text in the input changes.
items?Iterable<T>NoneThe options, when they are built from data with a render function.
allowsEmptyCollection?booleanfalseKeeps the list open when no option matches, so an empty message can show.
allowsCustomValue?booleanfalseAccepts text that matches no option.
menuTrigger?"focus" | "input" | "manual""input"What opens the list: focusing the input, typing, or only the trigger button.
isDisabled?booleanfalseDisables the field.
isInvalid?booleanfalseMarks the field as invalid.
isRequired?booleanfalseRequires a value before a form can be submitted.
name?stringNoneThe name used when the field is submitted with a form.
aria-label?stringNoneA label for the field when there is no visible Label.

ComboboxInput

The text field with its trigger button. It renders an InputGroup around an InputGroupInput, and accepts the props of an input. Children, such as an InputGroupAddon, render inside the group.

PropTypeDefaultDescription
showTrigger?booleantrueShows the chevron button that opens the list.
showClear?booleanfalseShows a clear button while the input holds text.
disabled?booleanfalseDisables the input and its buttons.
placeholder?stringNoneText shown while the input is empty.
className?stringNoneClasses merged onto the input group.

ComboboxContent

The popover that holds the list. It accepts the props of the React Aria Popover.

PropTypeDefaultDescription
placement?Placement"bottom"Where the list opens relative to the input.
offset?number6The distance from the input, in pixels.
crossOffset?number0The offset along the other axis, in pixels.
anchor?RefObject<HTMLDivElement | null>NoneAn element to anchor the list to, such as the chips group. Get one from useComboboxAnchor.

ComboboxList

The listbox, a React Aria ListBox. Pass renderEmptyState to show a ComboboxEmpty when nothing matches, and items with a render function to build options from data.

ComboboxItem

One option, a React Aria ListBoxItem with a check mark when selected. A string child also becomes its textValue.

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

ComboboxGroup, ComboboxLabel, ComboboxSeparator, ComboboxEmpty and ComboboxCollection

ComboboxGroup is a React Aria ListBoxSection, ComboboxLabel its heading, ComboboxSeparator a divider between groups, and ComboboxEmpty the message for an empty result. ComboboxCollection is React Aria's Collection, for rendering items inside a group from an array.

ComboboxChips, ComboboxChipList, ComboboxChip and ComboboxChipsInput

The parts of the multiple selection field. ComboboxChips is the bordered group, ComboboxChipList renders the selected items as a tag list, ComboboxChip is one tag (it takes id, and showRemove to hide its remove button) and ComboboxChipsInput is the text input, which removes the last chip on Backspace when it is empty.

ComboboxTrigger, ComboboxValue and useComboboxAnchor

ComboboxTrigger is a standalone button with a chevron for custom layouts, and ComboboxValue is the React Aria ComboBoxValue, which exposes the selected items to a render function. The clear button that showClear adds is internal to the file and is not exported. useComboboxAnchor returns a ref to pass to ComboboxContent as anchor.