Select

Picks one value from a list.

Type to jump to an item, and use the arrow keys to move through the list. SelectLabel names the select.

Preview
basic.tsx
import {
  Select,
  SelectContent,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "~/components/ui/select"

export default function Example() {
  return (
    <div className="grid w-56 gap-sm">
      <Select placeholder="Select a role">
        <SelectLabel>Role</SelectLabel>
        <SelectTrigger>
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="viewer">Viewer</SelectItem>
          <SelectItem value="commenter">Commenter</SelectItem>
          <SelectItem value="editor">Editor</SelectItem>
          <SelectItem value="owner" disabled>
            Owner
          </SelectItem>
        </SelectContent>
      </Select>
    </div>
  )
}

Dependencies

What it's built from and what's built from it in Base, read from the imports in its source.

UsesInputform itemLabelform itemScroll AreaprimitiveTextprimitive
Used byNothing yet.
Packages @ui-sdk/core@0.1.0-beta.20@ui-sdk/react@0.1.0-beta.20lucide-react@1.73.0

Installation

Set the project up for Base once first, as Getting started shows. Then add it with the CLI, or by hand.

With the CLI

terminal
npx shadcn@latest add https://design.zepez.dev/r/base/select.json

Manually

Install its packages:

terminal
npm install @ui-sdk/core@0.1.0-beta.20 @ui-sdk/react@0.1.0-beta.20 lucide-react@1.73.0

Add the components it uses first, listed under Dependencies.

Then copy the source:

components/ui/select.tsx
import {
  Select,
  SelectContent as SelectContentPrimitive,
  SelectItem as SelectItemPrimitive,
  SelectItemIndicator as SelectItemIndicatorPrimitive,
  SelectItemText,
  SelectLabel as SelectLabelPrimitive,
  SelectTrigger as SelectTriggerPrimitive,
  SelectValue as SelectValuePrimitive,
} from "@ui-sdk/react/select"
import { Check, ChevronDown } from "lucide-react"
import type * as React from "react"

import { inputVariants } from "~/components/ui/input"
import { labelVariants } from "~/components/ui/label"
import { ScrollArea } from "~/components/ui/scroll-area"
import { textVariants } from "~/components/ui/text"
import { cnState } from "~/lib/utils"

/** Names the select. */
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectLabelPrimitive>) {
  return (
    <SelectLabelPrimitive
      className={cnState(
        [labelVariants(), textVariants({ leading: "none" }), "flex w-fit"],
        className,
      )}
      {...props}
    />
  )
}

/** Opens the list. Holds a `SelectValue`; draws its own chevron. */
function SelectTrigger({
  className,
  children,
  ...props
}: React.ComponentProps<typeof SelectTriggerPrimitive>) {
  return (
    <SelectTriggerPrimitive
      className={cnState(
        [
          inputVariants(),
          textVariants({ size: "sm" }),
          "flex h-8 w-full min-w-40 cursor-pointer items-center justify-between gap-xs px-md whitespace-nowrap",
          "[&_svg]:pointer-events-none [&_svg]:shrink-0",
        ].join(" "),
        className,
      )}
      {...props}
    >
      {(state) => (
        <>
          {typeof children === "function" ? children(state) : children}
          <ChevronDown className="size-4 shrink-0 text-muted-foreground" />
        </>
      )}
    </SelectTriggerPrimitive>
  )
}

/** Shows the chosen item, or the select's `placeholder`. */
function SelectValue({ className, ...props }: React.ComponentProps<typeof SelectValuePrimitive>) {
  return (
    <SelectValuePrimitive
      className={cnState("truncate data-placeholder:text-muted-foreground", className)}
      {...props}
    />
  )
}

/** The list of items. As wide as the trigger, and scrolls when there isn't room. */
function SelectContent({
  className,
  children,
  sideOffset = 4,
  ...props
}: React.ComponentProps<typeof SelectContentPrimitive>) {
  return (
    <SelectContentPrimitive
      sideOffset={sideOffset}
      className={cnState(
        [
          textVariants({ size: "sm" }),
          "flex flex-col overflow-hidden m-0 max-h-(--available-height) min-w-(--anchor-width) rounded-lg border-0 bg-overlay text-overlay-foreground shadow-lg ring-1 ring-foreground/5 outline-none dark:ring-foreground/10",
          "origin-(--transform-origin) transition-[opacity,scale] duration-100 ease-out data-starting-style:scale-95 data-starting-style:opacity-0 data-ending-style:scale-95 data-ending-style:opacity-0 motion-reduce:transition-none",
        ].join(" "),
        className,
      )}
      {...props}
    >
      {(state) => (
        <ScrollArea className="min-h-0">
          <div className="p-2xs">{typeof children === "function" ? children(state) : children}</div>
        </ScrollArea>
      )}
    </SelectContentPrimitive>
  )
}

/** One choice. Shows a check mark while it's selected. */
function SelectItem({
  className,
  children,
  ...props
}: React.ComponentProps<typeof SelectItemPrimitive>) {
  return (
    <SelectItemPrimitive
      className={cnState(
        [
          textVariants({ size: "sm" }),
          "relative flex min-h-7 w-full cursor-default items-center gap-sm rounded-md py-xs pr-2xl pl-sm outline-none select-none",
          "data-highlighted:bg-accent data-highlighted:text-accent-foreground",
          "data-disabled:pointer-events-none data-disabled:opacity-50",
        ].join(" "),
        className,
      )}
      {...props}
    >
      {(state) => (
        <>
          <SelectItemText>
            {typeof children === "function" ? children(state) : children}
          </SelectItemText>
          <SelectItemIndicatorPrimitive className="absolute right-2 inline-flex size-4 items-center justify-center">
            <Check className="size-3.5" />
          </SelectItemIndicatorPrimitive>
        </>
      )}
    </SelectItemPrimitive>
  )
}

export { Select, SelectContent, SelectItem, SelectLabel, SelectTrigger, SelectValue }

API reference

Generated from Base's types. Props marked ours are added here; the rest come from the ui-sdk part it wraps. Every part also accepts its element's native attributes.

Select

Picks one value, or several, from a list in a popup. T is inferred from value, defaultValue, items or onValueChange, and multiple makes the value a list.

announcement

What screen readers hear after typing pauses in the search field, when no SelectStatus is rendered. Return null for nothing.

Type (change: ListAnnouncement) => string | null · Default "3 results", "No results" or "Loading"

autoComplete

A hint for the browser's autofill, like "country".

Type string

container

Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.

Type Element | DocumentFragment | null

controller

Opens, closes, reads and sets the select from anywhere. Create one with createSelectController().

Type { isOpen: () => boolean; setOpen: (open: boolean, options?: SelectChangeOptions<SelectOpenChangeReason>) => boolean; open: (options?: (SelectChangeOptions<...> & { ...; })) => Promise<...>; ... 7 more ...; focus: () => void; }

debug

Logs every state change with its reason to the console, in development builds.

Type boolean

defaultOpen

Whether the list starts open, when uncontrolled.

Type boolean · Default false

defaultQuery

The search field's text at first, when uncontrolled.

Type string

defaultValue

The values selected at first, when uncontrolled. A form reset returns to them. The value selected at first, when uncontrolled. A form reset returns to it. The value or values selected at first, when uncontrolled. A form reset returns to it.

Type T | T[] | ItemsOf<T> | null

disabled

Disables the select like a native one: it can't be focused or changed, and the value isn't submitted.

Type boolean

dismissible

Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass false while it holds unsaved work, and ask in onDismissAttempt.

Type boolean · Default true

emptyItems

Items shown instead of items while the search field is empty, like recent choices. Groups work, like { type: "group", label: "Recent", items }. Needs items and a SelectInput.

Type ListData<T>

filter

How a SelectInput narrows the list: "contains", "startsWith", a function of the item and the text, whose numeric result also sorts data items, or false to keep every item, for results a server already filtered.

Type ListFilter<T> · Default "contains"

form

The id of a form to belong to, when the select isn't inside that form.

Type string

isItemEqualToValue

Whether an item's value is the selected value, for object values that aren't the same object.

Type (itemValue: T, value: T) => boolean

items

The items as data. Renders the list for you, and lets the trigger show labels and find items by typing before the list has ever opened.

Type ListData<T>

itemToLabel

The text a value shows in the trigger, for values whose item isn't rendered, like async results.

Type (value: T) => string

itemToValue

The string an item's value submits as and is identified by, for object values. Strings pass through, and objects use their value or id.

Type (value: T) => string

loop

Whether arrow keys wrap from the last item to the first.

Type boolean · Default true

modal

"pointer": an outside press only closes the list. true: also locks scroll and makes the rest of the page inert. false: outside presses reach what they hit.

Type boolean | "pointer" · Default "pointer", or true while it presents as a sheet

multiple

Whether several items can be selected. The value is then a list, and the list stays open as items toggle. Whether several items can be selected. @defaultValue false

Type boolean · Default false

name

The name the value submits under. Without one, the select submits nothing.

Type string

onDismissAttempt

Runs when dismissible refused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here.

Type (details: { reason: "outside-press"; event?: MouseEvent; } | { reason: "escape-key"; event?: KeyboardEvent; } | { reason: "back"; event?: Event; } | { reason: "swipe"; event?: PointerEvent | TouchEvent; }) => void

onHighlight

Runs when the highlight moves, with the item's index among the visible items, so a virtualized list can scroll to it.

Type (value: T | null, details: ListHighlightDetails) => void

onLoadMore

Runs when the highlight or scrolling reaches the last item, so the next page can load, like createAsyncOptions's loadMore. Not again for the same items, unless the last load failed.

Type () => void

onOpenChange

Runs when the list wants to open or close. details.reason says why, and details.cancel() stops it.

Type (open: boolean, details: ChangeDetails<SelectOpenChangeReason>) => void

onOpenChangeComplete

Runs once the list has finished opening or closing, after any animation.

Type (open: boolean) => void

onQueryChange

Runs when the search field's text wants to change: typing, or closing the list, which empties it.

Type (query: string, details: TextChangeDetails<SelectQueryChangeReason>) => void

onValueChange

Runs when a user, a form reset or a controller wants to change the value. details.reason says why, and details.cancel() stops it.

Type ((value: T[], details: ChangeDetails<SelectValueChangeReason>) => void) | ((value: NoInfer<T> | null, details: ChangeDetails<SelectValueChangeReason>) => void) | ((value: NoInfer<T> | ... 1 more ... | null, details: ChangeDetails<...>) => void)

open

Whether the list is open. Pass it to control it.

Type boolean

placeholder

What the value shows while nothing is selected.

Type string

presentation

How the list presents. "sheet" slides it up from the bottom of the screen, where it can be swiped away, and "auto" does that on small touch screens. Decided each time it opens; the server renders "popover" for "auto".

Type PresentationSetting<"popover"> · Default "popover"

query

The text in the search field, which filters the list. Pass it to control it. Closing the list empties it.

Type string

readOnly

Keeps the select focusable and its value submitted, but stops changes.

Type boolean

required

Blocks form submission until a value is selected, with the browser's own message.

Type boolean

status

Whether results are loading or failed, for the status and empty parts. Sets aria-busy on the list while loading.

Type AsyncOptionsStatus · Default "idle"

value

The selected values. Pass it to control the select. The selected value. Pass it to control the select. null selects nothing. The selected value, or values with multiple. Pass it to control the select.

Type T | T[] | ItemsOf<T> | null

virtualFocus

Keeps focus on the trigger while the list is open, as on a native select: arrow keys, Home, End and typing move the highlight, and the trigger points at the highlighted item with aria-activedescendant. A search field in the list still takes focus.

Type boolean · Default false

SelectContent

The list of items. As wide as the trigger, and scrolls when there isn't room.

align

How the popup lines up with the anchor along that side. start and end follow the reading direction. How the list lines up with the trigger along that side.

Type "center" | "start" | "end" · Default "start"

alignItemWithTrigger

Whether the list overlaps the trigger so the selected item sits on it, like a native select on macOS. Falls back to opening below when there isn't room, and for touch.

Type boolean · Default false

alignOffset

Shift along the anchor, in pixels. Shift along the trigger, in pixels.

Type number · Default 0

anchor

Positions the popup against this instead of its trigger: an element, a CSS selector, a point like { x, y }, or anything with getBoundingClientRect(). It's read on every check, so it can move. A controller's open({ anchor }) wins for that open.

Type string | Anchor | null

arrowPadding

Space to keep between the arrow and the popup's corners, in pixels.

Type number · Default 6

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: SelectContentState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: SelectContentState) => string)

collisionPadding

Space to keep from the viewport edges, in pixels.

Type number · Default 8

container

Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.

Type Element | DocumentFragment | null

keepMounted

Whether the list stays in the page, hidden, while closed. Its content keeps its state between opens.

Type boolean · Default false

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<SelectContentState>

side

Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the trigger the list opens on.

Type "start" | "end" | "top" | "bottom" | "left" | "right" · Default "bottom"

sideOffset

Gap between the anchor and the popup, in pixels. Gap between the trigger and the list, in pixels.

Type number · Default 4

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: SelectContentState) => CSSProperties)

SelectItem

One choice. Shows a check mark while it's selected.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: SelectItemState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: SelectItemState) => string)

disabled

Keeps the item from being chosen. The keyboard and the pointer skip it. Sets data-disabled and aria-disabled.

Type boolean

index

The item's position among all items, for virtualized lists that render only some. Sets aria-posinset and aria-setsize.

Type number

label

The text the trigger shows and typing finds, when the content isn't plain text. Not the accessible name: use aria-label for that.

Type string

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<SelectItemState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: SelectItemState) => CSSProperties)

value*

What the value becomes when the item is chosen. A string, or any value with itemToValue.

Type unknown

SelectLabel

Names the select.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: {}) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: {}) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<{}>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: {}) => CSSProperties)

SelectTrigger

Opens the list. Holds a SelectValue; draws its own chevron.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: SelectTriggerState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: SelectTriggerState) => string)

controller

Connects a trigger outside the select to the select with this controller.

Type { isOpen: () => boolean; setOpen: (open: boolean, options?: SelectChangeOptions<SelectOpenChangeReason>) => boolean; open: (options?: (SelectChangeOptions<...> & { ...; })) => Promise<...>; ... 7 more ...; focus: () => void; }

disabled

Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless focusableWhenDisabled is set.

Type boolean · Default false

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<SelectTriggerState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: SelectTriggerState) => CSSProperties)

SelectValue

Shows the chosen item, or the select's placeholder.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: SelectValueState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: SelectValueState) => string)

getMoreLabel

The words for the labels past maxLabels.

Type (count: number) => string · Default (count) => `${count} more`

maxLabels

With multiple, how many labels show before the rest are counted, as in "Apple, Banana and 2 more", joined the way the page's language joins lists, or in English with the default getMoreLabel.

Type number

placeholder

What shows while nothing is selected. Overrides the select's placeholder.

Type string

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<SelectValueState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: SelectValueState) => CSSProperties)