Select

size
pin
placeholder
label
multiple
filterable
disabled
hasClear
hasCounter

Select is a control that provides a list of options that a user can select.

import {Select} from '@gravity-ui/uikit';

[!NOTE] In v8 the options are drawn by the new list. What changed for a consumer is collected in the migration guide.

Options

Options to select.

Defining options

You can define options as an array of objects or as the children of a component. The first approach is useful for cases where options require complex preparation and, possibly, memorization. The second one is convenient when there are few options, and their configuration does not require complex calculations.

In a React Server Component Select.Option and Select.OptionGroup are not reachable: use the named SelectOption and SelectOptionGroup instead. Their props types are SelectOptionProps and SelectOptionGroupProps.

Flat list

The text of an option

The text of an option is what the trigger shows for a selected option, what the filter matches and what the search by the first letters looks up. By default it is the content of the option when that is a string or a number, its children when those are, and its value otherwise — so an option that renders anything but a plain string needs getOptionText, or it will be searched and named by its value.

useSelectOptions takes the same property: pass it there as well when the options are filtered outside of the component. Define the function outside the component or memoize it — it takes part in the memoization of the list, and a new function on every render rebuilds the rows.

getOptionText replaces the text property of an option, which is gone: the text of an option is asked for rather than stored, so one function covers every option instead of a field repeated on each of them.

The value of an option identifies its row, so the values have to be unique across the whole list, groups included (for a non-string value — its key). The DOM id of the row is derived from it, and that id is what aria-activedescendant of the trigger points at — read it from there rather than building it by hand: the escaping of a value belongs to the list and is not a contract.

Grouped list

A group header is a caption rather than an option: it carries role="presentation", stays out of the keyboard walk and out of the count of role="option" rows, and describes the options under it through aria-describedby. A group whose label is empty draws a separating line instead of a header — as the first row of the list it has nothing to separate and takes no space at all. That is the default drawing of a group: renderOptionGroup and getOptionGroupHeight are asked first and render and measure whatever they like, empty label or not.

Storing data in options

You can define and store unique data in each option by using the option.data property. This can be useful when you need to enrich the data when using the onUpdate callback or, for example, when drawing your options with renderOption.

Non-string values

The value of an option can be of any type: the type of value, defaultValue and onUpdate follows the options. The Select knows a value by a string key — the id of its row, the field of a form and the comparison of two values all use it. A string is its own key, another primitive is turned into one with String(), and an object needs getValueKey. Values with equal keys are one value: an object from a new response selects the option it matches. Define getValueKey outside the component or memoize it, as getOptionText.

An object value has no text of its own: give the option a string content or pass getOptionText. A Select.Option child takes a string unless its type is named: <Select.Option<unknown, number> value={1}>; the Select itself takes the type from value or a typed onUpdate={(value: number[]) => …}. A selected value with no option is shown by its key; keep its option in options or render it with renderSelectedOptions. A form submits keys, not values. In a union type 1 and "1" share a key and are one value.

Nullable values

'', null and undefined mean no value unless an option declares them. Without an option such a value has no text, clear button or count, a form sends it as '', while value and onUpdate keep it as is. 0 and false are always values.

Selecting multiple options

To enable multiple selection, use the multiple property. Its default value is false.

Shift+click, Shift+↑/↓ and Shift+Space select a range of options, from the option chosen last to the target.

Counter

You can add a counter of the selected items to the component using the hasCounter property.

Filtering options

To enable filter section, use the filterable property. Its default value is false.

The search by the first letters

With the popup open and no filter in the way, the character keys look up an option: the list moves the activity to the first option whose text starts with what was typed, the buffer resets a second after the last key, and repeating one character cycles through the options that start with it. A space belongs to the query while it is being typed, so a label with a space in it is reachable — and it selects nothing until the buffer is empty again. A character the list took for its search does not reach the hotkeys of the application around it.

In a filterable Select the keys go into the filter instead: typing there is filtering.

Size

To manage the default control and option size, use the size property. Its default size is m.

Control width

By default, the control width stretches to match the width of the content of the selected options. You can manage it by using the width property:

'max': Stretches to the full width of the parent.

number: Applies width in pixels.

You can manage the popup width with the popupWidth property. The available values are:

'fit': Apply control width.

number: Apply width in pixels.

Points to note about the default behavior:

  • The popup width is equal to the width of the widest option, but not wider than 90vw. This does not apply to a virtualized Select.

  • Narrow options are stretched to fit the width of the control.

Virtualized list

A long list of options is rendered row by row unless you ask for otherwise: every option is a DOM row. To render only the visible ones, wrap the Select in ListVirtualizer from the @gravity-ui/uikit/virtualizer entry point — the wrapper needs no configuration, and the popup keeps working through the portal. A couple of hundred options is where it starts to pay off; above 150 the Select says so in a development warning.

The entry point needs @tanstack/react-virtual: it is an optional peer dependency of the package and has to be installed alongside it.

import {Select} from '@gravity-ui/uikit';
import {ListVirtualizer} from '@gravity-ui/uikit/virtualizer';

<ListVirtualizer>
  <Select options={thousandsOfOptions} />
</ListVirtualizer>;

The wrapper does not have to stand next to the Select: one wrapper with minItemsCount at the root of the app covers every Select below it. A Select of fewer options renders as if there were no wrapper — every option a DOM row, the popup as wide as the widest option. The Select counts all of its options, without the group headers and without the filter, so typing does not switch the list.

import {Provider} from '@gravity-ui/uikit';
import {ListVirtualizer} from '@gravity-ui/uikit/virtualizer';

<Provider theme="light">
  <ListVirtualizer minItemsCount={50}>
    <App />
  </ListVirtualizer>
</Provider>;

To change the settings for one Select, put a second wrapper right around it. It changes only what it is given and takes the rest from the one at the root: overscan={20} keeps the threshold, minItemsCount={0} virtualizes that Select whatever the number of its options, and minItemsCount={Infinity} keeps it plain.

import {Select} from '@gravity-ui/uikit';
import {ListVirtualizer} from '@gravity-ui/uikit/virtualizer';

// Under the wrapper at the root: this Select is virtualized whatever the number of its options
<ListVirtualizer minItemsCount={0}>
  <Select options={options} />
</ListVirtualizer>;

The code of the virtualizer is a chunk of its own, and it is not loaded for the shorter Selects. A Select that is going to be virtualized starts loading it on mount; a popup opened before it arrives shows its first options until the window takes over, and scrolls to the selected one then.

Things to keep in mind about a virtualized Select:

  • The popup width no longer gets adjusted to the length of the longest option.

  • The minimum width of the popup is equal to the width of the control, or 100px if the control is shorter.

  • The height of a row before it is rendered is taken from getOptionHeight and the size of the Select; the estimateItemSize of the wrapper is not used, since the type of an option row does not leave the Select — passing it writes a warning in development. The measure and overscan properties of the wrapper work as described for the List.

  • A popup rendered on the server gets its first options instead of the window — there is no viewport to measure it against — and the window takes over after hydration.

  • The wrapper covers the list of this Select, the one renderPopup puts on the page included. A list inside a row of it, or a Select placed in such a row, renders every row of its own instead: the virtualization of a list does not reach what its rows draw.

  • Define getOptionHeight and renderOption outside the component or memoize them: a new function on every render makes the virtualizer start its measurements over and the rows re-render.

Accessible name

The trigger needs a name: label, aria-label, aria-labelledby or a <label htmlFor> pointing at the id of the Select. label names the trigger and stays out of its value; a placeholder is not a name. With renderControl the label is not drawn, so name the custom control yourself.

Advanced usage

There are many ways to customize your Select.

Rendering custom control

To render a custom control, use the renderControl property.

Hand ref to your element and spread triggerProps onto it: they open and close the popup, carry the keyboard of the list and the ARIA of the combobox (role, aria-expanded, aria-controls, aria-activedescendant). A control that keeps them to itself neither opens nor navigates. triggerProps also contains disabled. Cast the generic ref to a button ref when using Button.

Rendering custom filter section

To render a custom filter section, use the renderFilter property and set the filterable property to true.

inputProps carries everything the input of a combobox needs: the value, the handlers, the placeholder and the ARIA wiring — role, aria-label, aria-controls, aria-activedescendant, aria-expanded, aria-autocomplete. It also carries size: 1, a width hint rather than ARIA: it lets the input shrink to the popup instead of keeping the twenty characters an input asks for by default. Without them the filter has no accessible name and names no active option for a screen reader. Spread it onto a plain input together with ref. A component with an API of its own — TextInput, say — takes the props it owns (value, placeholder, onChange, onKeyDown) and hands the rest to the element through controlProps, which one line of destructuring does; onKeyDown must be among them, it carries the whole keyboard of the list.

Rendering custom options

To render custom options, use the renderOption property. It is called with the option and with the state of its row: isItemActive, whether the row is the active one (the one Enter applies); selected, whether the option is selected; and itemHeight, the height the row comes out as — the one getOptionHeight returned or the minimum of the size. The row itself shows the selection beside whatever this renders: a check mark in a multiple Select and a highlight in a single one. An option that draws its own indication — a Radio or a Checkbox from selected — turns that off with selectionStyle="none"; without one of its own the selection becomes invisible. Such a control is decoration — the row selects the option, and an interactive element is not allowed inside it: wrap the control in an element with inert (inert="" before React 19) and keep the text of the option outside it.

renderOptionGroup is the same for the header of a group: the group and {isItemActive, itemHeight}.

Rendering custom selected options

To render the selection in the control, use the renderSelectedOptions property. It is called with all the selected options in the order of value — an array of one in a single select — and only when there is a value. A value without an option comes as {value}, without content. Give the returned elements keys when they hold state. The label, placeholder, counter and clear button stay with the Select. Without the property the control shows the texts of the options joined with , .

Rendering options with different heights

A row is as tall as its content, and no shorter than the minimum of its size (24, 28, 36 and 44 pixels, as the control of the same size; on mobile every row takes the 44 of xl) — unless you set the height yourself. If you need to render options with different heights, you can use the option.data property. It will store information about what height you need to set for the options, as well as the getOptionHeight property to set this value: the number it returns becomes the height of the row and the estimate the virtualizer positions the rows with.

Rendering custom counter

To render a custom counter, use the renderCounter property. The counter is only displayed when multiple selection is enabled (multiple={true}) and hasCounter={true}.

Rendering options list

The renderPopup property allows you to control the content of the options list: change the order of standard elements (filter, list), hide them, or add custom elements between, before, or after them.

Error

This Select state is for incorrect user input. To change the Select appearance, use the validationState property with the "invalid" value. Optionally, you can provide an error message through the errorMessage property. By default, the message text is rendered outside the component. You can change this with the errorPlacement property.

Properties

NameDescriptionTypeDefault
classNameControl classNamestring
defaultValueDefault values that represent selected options in case of using an uncontrolled stateV[]
disabledShows that the user cannot work with the controlbooleanfalse
filterableShows that select popup has a filter sectionbooleanfalse
filterOptionUsed to compare option with filterfunction
filterPlaceholderDefault filter input placeholder textstring
getOptionTextThe text of an option: the trigger, the filter and the search by the first letters use itfunctionstring content, otherwise the value
getValueKeyThe string key of a value: the id of its row, the form field, the equality of values(value: V) => stringthe string itself, String() for another primitive
getOptionHeightUsed to set height of customized user optionsfunction
getOptionGroupHeightUsed to set height of customized user option groupfunction
hasClearEnables displaying icon for clearing selected optionsbooleanfalse
idid HTML attributestring
labelControl label; on mobile also the title of the sheetstring
loadingAdds the loading item to the end of the option list. Works like a persistent loading indicator while the options list is empty.boolean
multipleShows whether multiple options can be selected in the listbooleanfalse
nameName of the controlstring
onBlurHandler that is called when the element loses focus.function
filterControlled filter valuestring''
onFilterChangeFires every time after changing the filterfunction
onFocusHandler that is called when the element gets focusfunction
onLoadMoreFires when the loading indicator gets visiblefunction
onOpenChangeFires every time after changing popup visibilityfunction
onUpdateFires when an alteration to the Select value is committed by the userfunction
optionsOptions to selectSelectOptions
pinControl border viewstring'round-round'
placeholderPlaceholder textstring
popupClassNamePopup with the option list classNamestring
popupPlacementPopup placementPopupPlacement Array<PopupPlacement>['bottom-start', 'bottom-end', 'top-start', 'top-end']
popupWidthPopup widthnumber | 'fit'
sheetClassNameSheet's classNamestring
qaTest id attribute (data-qa)string
renderControlUsed to render user controlfunction
renderCounterUsed to render user counter. Works only with hasCounter.function
renderEmptyOptionsUsed to render a node for an empty option listfunction
renderFilterUsed to render user filter sectionfunction
renderOptionUsed to render user optionsfunction
renderOptionGroupUsed to render user option groupsfunction
renderSelectedOptionsUsed to render the selection in the controlfunction
renderPopupUsed to render options list contentfunction
selectionStyleHow a row shows that its option is selected: the check mark or highlight (auto) or nothing (none)'auto' | 'none''auto'
sizeControl / options sizestring'm'
valueValues that represent selected optionsV[]
viewControl viewstring'normal'
widthControl widthstring | numberundefined
errorMessageError textstring
errorPlacementError positionoutside insideoutside
validationStateValidation state"invalid"
hasCounterShows the selected option count. The counter appears only when the multiple selection is enabled.boolean

CSS API

The class names of the markup are not a public contract — the rows of the popup are rendered by the list and its row view, and their markup changes with the kit. What is supported:

  • the variables below;
  • the look of a row, through the --g-list-item-view-* variables of the row view: its colours, and its height, padding and radius, which otherwise follow the size of the Select. Set them on popupClassName or sheetClassName — for example --g-list-item-view-min-height: 48px for taller rows on mobile. The estimate of the virtualizer and the itemHeight of renderOption still come from the size: when the exact number matters, use getOptionHeight;
  • the content of a row, through renderOption, renderOptionGroup and renderSelectedOptions.
NameDescription
--g-select-focus-outline-colorOutline color if focused (missing by default)