Перейти к основному содержанию

Обзор

Используйте Select для значения формы, выбираемого из списка. Dropdown остается основным высокоуровневым API для меню, средств выбора, панелей и страниц, объединяющих эти рабочие процессы.

Использование

Неконтролируемое состояние

Используйте defaultValue, чтобы задать начальный приоритет. Компонент выбора управляет последующими изменениями выбора.
Передайте items в Root, чтобы Value отображал метку выбранного элемента; без него триггер показывает необработанное значение. Выбранное значение может быть null, если ничего не выбрано.

Структура

Скомпонуйте публичные части внутри Select.Root. Trigger и Item отображают только свои дочерние элементы. Явно добавьте Icon, ItemText и ItemIndicator, если нужны стандартные шеврон, метка и флажок.
Portal, List, Backdrop, стрелки и индикаторы являются необязательными. Используйте Positioner вокруг Popup для позиционирования, в том числе когда отображаете всплывающее окно встроенно без портала.

Контролируемое состояние

Передайте value и обновляйте его с помощью onValueChange, чтобы управлять тем же приоритетом в состоянии React. Функция обратного вызова получает следующее значение и сведения о событии.

Множественный выбор

С multiple значение представляет собой массив. Для неконтролируемого множественного выбора используйте defaultValue={['en']} вместо value и onValueChange. Обобщённые типы корневого компонента представляют значение варианта и то, включён ли множественный выбор.

Состояние открытия

Выбор и видимость всплывающего окна не зависят друг от друга. В приведенных выше примерах видимость всплывающего окна остается неконтролируемой. Выбор одного значения закрывает всплывающее окно; при множественном выборе оно остается открытым. Используйте defaultOpen, чтобы задать его начальную видимость; по умолчанию используется false. Передайте open и обновляйте его с помощью onOpenChange, чтобы управлять видимостью. Этот пример управляет всплывающим окном, оставляя выбранный приоритет неконтролируемым.

Композиция с полем

Оберните компонент выбора в Field.Root, чтобы связать его триггер с видимой меткой и вспомогательным текстом. Поле обрабатывает маркировку и валидацию; компонент выбора сохраняет собственное состояние выбора и всплывающего окна.

Компоновка элемента

Комбинируйте произвольное содержимое внутри Item. Поместите доступную для поиска метку в ItemText; дополнительное содержимое не становится его меткой для поиска по мере ввода. Передайте дочерние элементы в Icon или ItemIndicator, чтобы заменить их стандартные значки, либо полностью опустите эти части.
Все части, отображающие элементы, поддерживают нативные атрибуты, refs и API композиции render, className и style из Base UI. Например, используйте render={<Button />} в Trigger, чтобы скомпоновать его с кнопкой Twenty UI. Для элемента render, не являющегося кнопкой, также установите nativeButton={false}.

Размещение

Задайте size="sm" или size="md" для Trigger. Размещение задаётся в Positioner; назначение портала задаётся в Portal. Positioner сохраняет значения по умолчанию Base UI: side="bottom", align="center", sideOffset={0} и alignItemWithTrigger={true}. Выравнивание выбранного элемента применяется для ввода указателем, когда достаточно места. Установите alignItemWithTrigger={false}, чтобы последовательно использовать позиционирование с привязкой к якорю. В приведённых выше примерах явно выбраны align="start" и sideOffset={8}.
Positioner также поддерживает виртуальные якоря, функции смещения, arrowPadding и disableAnchorTracking. Portal использует контейнер портала темы, если вы не предоставите container. Явно указанный container={null} ожидает, пока этот контейнер станет доступен.

Нативные формы и сведения о колбэках

Установите name в Root, чтобы включить выбранное значение в FormData. При множественном выборе отправляется одна запись для каждого выбранного значения. form связывает скрытое поле ввода с внешней формой, а inputRef предоставляет доступ к этому полю. required, disabled и autoComplete сохраняют нативное поведение форм Base UI. onValueChange и onOpenChange получают следующее состояние и сведения о вышестоящем событии, включая reason, нативное event, cancel() и allowPropagation(). Вызов cancel() предотвращает соответствующее внутреннее изменение состояния. Для управляемых корневых компонентов по-прежнему требуется обновлять value или open.
Обобщённые типы корневого компонента представляют значение варианта и то, включён ли множественный выбор. Значения-объекты поддерживают itemToStringLabel, itemToStringValue и isItemEqualToValue. Используйте null для пустого одиночного выбора и пустой массив для пустого множественного выбора.

Клавиатура

Пользователи клавиатуры могут открыть список с помощью триггера, перемещаться по вариантам клавишами со стрелками и вводить текст для поиска варианта. Home и End переходят к первому и последнему вариантам. Enter выбирает вариант; Escape закрывает всплывающее окно и возвращает фокус триггеру. При множественном выборе всплывающее окно остаётся открытым при переключении вариантов. Добавьте триггеру метку с помощью Select.Label, доступного имени или Field. Один лишь заполнитель не задаёт имя элементу управления.

Свойства

Справочник генерируется из публичных типов компонентов. Нативные атрибуты, включая доступные имена и обработчики событий, также принимаются частями, которые отображают элементы.

Select.Root

RefObject<SelectRootActions | null>
A ref to imperative actions.
  • unmount: Ends the closing phase of the select after an externally controlled closing animation finishes. Call preventUnmountOnClose() in onOpenChange first, otherwise the select completes closing on its own. Whether it leaves the DOM is decided by keepMounted on the portal.
  • close: Closes the select imperatively when called.
string
Provides a hint to the browser for autofill.
ReactNode
Select parts sharing selection, open state and accessible relationships. Root renders no DOM node.
boolean
по умолчанию:"false"
Whether the select popup is initially open.To render a controlled select popup, use the open prop instead.
SelectInputValue<Value, Multiple> | null
The uncontrolled value of the select when it’s initially rendered.To render a controlled select, use the value prop instead.
boolean
по умолчанию:"false"
Whether the component should ignore user interaction.
string
Identifies the form that owns the hidden input. Useful when the select is rendered outside the form.
boolean
по умолчанию:"true"
Whether moving the pointer over items should highlight them. Disabling this prop allows CSS :hover to be differentiated from the :focus (data-highlighted) state.
string
The id of the Select.
Ref<HTMLInputElement>
Ref to the native hidden input used for form submission.
((itemValue: Value, value: Value) => boolean)
Custom comparison logic used to determine if a select item value matches the current selected value. Useful when item values are objects without matching referentially. Defaults to Object.is comparison.
Record<string, ReactNode> | readonly { label: ReactNode; value: any; }[] | readonly Group<any>[]
Data structure of the items rendered in the select popup. When specified, <Select.Value> renders the label of the selected item instead of the raw value.
((itemValue: Value) => string)
When the item values are objects (<Select.Item value={object}>), this function converts the object value to a string representation for display in the trigger. If the shape of the object is { value, label }, the label will be used automatically without needing to specify this prop.
((itemValue: Value) => string)
When the item values are objects (<Select.Item value={object}>), this function converts the object value to a string representation for form submission. If the shape of the object is { value, label }, the value will be used automatically without needing to specify this prop.
boolean
по умолчанию:"true"
Determines if the select enters a modal state when open.
  • true: user interaction is limited to the select: document page scroll is locked and pointer interactions on outside elements are disabled.
  • false: user interaction with the rest of the document is allowed.
On touch devices, a true modal blocks outside taps but leaves the page scrollable unless the popup spans nearly the full viewport width, matching native iOS behavior.
boolean
по умолчанию:"false"
Whether multiple items can be selected.
string
Identifies the field when a form is submitted.
((open: boolean, eventDetails: SelectRootOpenChangeEventDetails) => void)
Receives the requested open state and unchanged Base UI event details.
((open: boolean) => void)
Event handler called after any animations complete when the select popup is opened or closed.
((value: SelectOutputValue<Value, Multiple> | (Multiple extends true ? never : null), eventDetails: SelectRootChangeEventDetails) => void)
Receives the requested generic value and unchanged Base UI event details, including reason, event and cancel(). Multiple selection receives an array; a cleared single value is null.
boolean
Whether the select popup is currently open.
boolean
по умолчанию:"false"
Whether the user should be unable to choose a different option from the select popup.
boolean
по умолчанию:"false"
Whether the user must choose a value before submitting a form.
SelectInputValue<Value, Multiple> | null
The value of the select. Use when controlled.

Select.Label

string | ((state: FieldRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, FieldRootState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: FieldRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Trigger

ReactNode
Trigger content rendered as supplied. Compose Value and Icon explicitly.
string | ((state: SelectTriggerState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
Whether the component should ignore user interaction.
boolean
по умолчанию:"true"
Whether the component renders a native <button> element when replacing it via the render prop. Set to false if the rendered element is not a button (for example, <div>).
Ref<HTMLButtonElement>
Ref to the rendered trigger element, a button by default.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectTriggerState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
"md" | "sm"
по умолчанию:"md"
Visual size of the trigger. Defaults to md.
CSSProperties | ((state: SelectTriggerState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Value

ReactNode | ((value: any) => ReactNode)
Accepts a function that returns a ReactNode to format the selected value. Treat the value as read-only: in multiple mode it may be a shared frozen array when nothing is selected.
string | ((state: SelectValueState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactNode
The placeholder value to display when no value is selected. This is overridden by children if specified, or by a null item’s label in items.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectValueState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectValueState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Icon

ReactNode
по умолчанию:"<IconChevronDown />"
Trigger icon content. Defaults to the Twenty chevron; explicit children replace it.
string | ((state: SelectIconState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectIconState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectIconState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Portal

string | ((state: SelectPortalState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
HTMLElement | ShadowRoot | RefObject<HTMLElement | ShadowRoot | null> | null
Portal destination. Defaults to the current theme container, then the document body. Explicit null waits for a container before mounting.
Ref<HTMLDivElement>
Ref to the portal div. Native props and render apply to this element.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectPortalState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectPortalState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Backdrop

string | ((state: SelectBackdropState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectBackdropState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectBackdropState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Positioner

"center" | "end" | "start"
по умолчанию:"center"
How to align the popup relative to the specified side.
boolean
по умолчанию:"true"
Uses the upstream selected-item alignment by default. Set false to use side, align and offsets without overlapping the trigger.
number | OffsetFunction
по умолчанию:"0"
Additional offset along the alignment axis in pixels. Also accepts a function that returns the offset to read the dimensions of the anchor and positioner elements, along with its side and alignment.The function takes a data object parameter with the following properties:
  • data.anchor: the dimensions of the anchor element with properties width and height.
  • data.positioner: the dimensions of the positioner element with properties width and height.
  • data.side: which side of the anchor element the positioner is aligned against.
  • data.align: how the positioner is aligned relative to the specified side.
Element | VirtualElement | RefObject<Element | null> | (() => Element | VirtualElement | null) | null
An element to position the popup against. By default, the popup will be positioned against the trigger.
number
по умолчанию:"5"
Minimum distance to maintain between the arrow and the edges of the popup.Use it to prevent the arrow element from hanging out of the rounded corners of a popup.
string | ((state: SelectPositionerState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
CollisionAvoidance
Determines how to handle collisions when positioning the popup.side controls overflow on the preferred placement axis (top/bottom or left/right):
  • 'flip': keep the requested side when it fits; otherwise try the opposite side (top and bottom, or left and right).
  • 'shift': never change side; keep the requested side and move the popup within the clipping boundary so it stays visible.
  • 'none': do not correct side-axis overflow.
align controls overflow on the alignment axis (start/center/end):
  • 'flip': keep side, but swap start and end when the requested alignment overflows.
  • 'shift': keep side and requested alignment, then nudge the popup along the alignment axis to fit.
  • 'none': do not correct alignment-axis overflow.
fallbackAxisSide controls fallback behavior on the perpendicular axis when the preferred axis cannot fit:
  • 'start': allow perpendicular fallback and try the logical start side first (top before bottom, or left before right in LTR).
  • 'end': allow perpendicular fallback and try the logical end side first (bottom before top, or right before left in LTR).
  • 'none': do not fallback to the perpendicular axis.
When side is 'shift', explicitly setting align only supports 'shift' or 'none'. If align is omitted, it defaults to 'flip'.
Boundary
по умолчанию:"clipping-ancestors"
An element or a rectangle that delimits the area that the popup is confined to.
Padding
по умолчанию:"5"
Additional space to maintain from the edge of the collision boundary.
boolean
по умолчанию:"false"
Whether to disable the popup from tracking any layout shift of its positioning anchor.
"absolute" | "fixed"
по умолчанию:"absolute"
Determines which CSS position property to use.
Ref<HTMLDivElement>
Ref to the positioning div. Native props, styles and render apply to this element.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectPositionerState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
"bottom" | "inline-end" | "inline-start" | "left" | "right" | "top"
по умолчанию:"bottom"
Which side of the anchor element to align the popup against. May automatically change to avoid collisions.
number | OffsetFunction
по умолчанию:"0"
Distance between the anchor and the popup in pixels. Also accepts a function that returns the distance to read the dimensions of the anchor and positioner elements, along with its side and alignment.The function takes a data object parameter with the following properties:
  • data.anchor: the dimensions of the anchor element with properties width and height.
  • data.positioner: the dimensions of the positioner element with properties width and height.
  • data.side: which side of the anchor element the positioner is aligned against.
  • data.align: how the positioner is aligned relative to the specified side.
boolean
по умолчанию:"false"
Whether to maintain the popup in the viewport after the anchor element was scrolled out of view.
CSSProperties | ((state: SelectPositionerState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Popup

ReactNode
Popup content rendered as supplied. Compose inside Positioner and choose Portal separately.
string | ((state: SelectPopupState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean | RefObject<HTMLElement | null> | ((closeType: InteractionType) => boolean | void | HTMLElement | null)
Determines the element to focus when the select popup is closed.
  • false: Do not move focus.
  • true: Move focus based on the default behavior (trigger or previously focused element).
  • RefObject: Move focus to the ref element.
  • function: Called with the interaction type (mouse, touch, pen, or keyboard). Return an element to focus, true to use the default behavior, or false/undefined to do nothing.
Ref<HTMLDivElement>
Ref to the popup div. Native props, styles and render apply to this element.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectPopupState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectPopupState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.List

string | ((state: SelectListState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectListState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectListState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Item

ReactNode
Option content rendered as supplied. Compose ItemText and an optional ItemIndicator explicitly.
string | ((state: SelectItemState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"false"
Whether the component should ignore user interaction.
string
Specifies the text label to use when the item is matched during keyboard text navigation.Defaults to the item text content if not provided.
boolean
по умолчанию:"false"
Whether the component renders a native <button> element when replacing it via the render prop. Set to true if the rendered element is a native button.
Ref<HTMLElement>
Ref to the rendered option element. Native props and render apply to this element.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectItemState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectItemState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
any
по умолчанию:"null"
A unique value that identifies this select item.

Select.ItemIndicator

ReactNode
Selected indicator content. Defaults to the Twenty check icon; explicit children replace it.
string | ((state: SelectItemIndicatorState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
Whether to keep the HTML element in the DOM when the item is not selected.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectItemIndicatorState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectItemIndicatorState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.ItemText

string | ((state: SelectItemTextState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectItemTextState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectItemTextState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Arrow

string | ((state: SelectArrowState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectArrowState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectArrowState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.ScrollDownArrow

string | ((state: SelectScrollDownArrowState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"false"
Whether to keep the HTML element in the DOM while the select popup is not scrollable.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectScrollDownArrowState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectScrollDownArrowState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.ScrollUpArrow

string | ((state: SelectScrollUpArrowState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"false"
Whether to keep the HTML element in the DOM while the select popup is not scrollable.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectScrollUpArrowState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectScrollUpArrowState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Group

string | ((state: SelectGroupState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectGroupState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectGroupState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.GroupLabel

string | ((state: SelectGroupLabelState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectGroupLabelState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectGroupLabelState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Select.Separator

string | ((state: SelectSeparatorState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
"horizontal" | "vertical"
по умолчанию:"horizontal"
The orientation of the separator.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SelectSeparatorState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SelectSeparatorState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.