Input · Select
Select
The user can select one or more options from a set of options through the Select selector and present the final selection result

Demos

How to import

Basic Usage

Each Option tag must declare the value attribute, and the Option children content will be rendered to the drop-down list

Pass Option as an array

You can pass an array of objects directly through optionList. Each object must contain the value / label attribute.

Multi-choice

Configuration multiple properties that can support multi-selection
Configuration maxTagCount. You can limit the number of options displayed, and the excess will be displayed in the form of + N
Configuration max Properties can limit the maximum number of options and cannot be selected beyond the maximum limit, while triggeringOn Exceedcallback

With Group

Grouping Option with OptGroup(Only supports the declaration of children through jsx, and does not support pass in through optionList)

Different sizes

Size: small / default / large

Different validate status

validateStatus: default / warning / error

Configure Prefix, Suffix, Clear Button

  • You can pass the selection box prefix through prefix, the selection box suffix through suffix, for text or React Node
    The left and right padding is automatically brought when the content passed in by prefix and reactix is text or Icon. If it is a custom ReactNode, the left and right padding is 0.
  • Whether to show the clear button is displayed by showClear
  • Whether to show the right drop-down arrow is displayed by showArrow

Select with inset label

By settinginsetLabel, you can set a label for Select, you can pass in string or ReactNode
When the incoming type is ReactNode, you need to handle the padding between the label and the text.

Additional items

We have reserved two slots at the bottom of the pop-up layer, which you can use when you need to add a custom node to the pop-up layer.
UseinnerTopSlot or outerTopSlot to pass the custom node, which will be rendered at the top of the pop-up layer. UseinnerBottomSlot or outerBottomSlot instead at the bottom.
  • innerTopSlot and innerBottomSlot will be rendered inside the Option List
  • outerTopSlot and outerBottomSlot will be rendered to level with the option List
Using outerTopSlot to insert content

Controlled component

When value is passed, Select is a controlled component, and the value selected is entirely determined by value.

Linkage Select

If it is a complex linkage with a hierarchical relationship, it is recommended to use Cascader components directly
You can turn on the search capability by setting filter to true.
The default search strategy will include comparison of the input value with the label value of option
By default, the search keywords will be cleared automatically after multiple selection is selected. If you want to keep it, you can turn off the default behavior by setting autoClearSearchValue to false (provided after v2.3)
A multi-select example with remote search, request debounce, loading status.
  • Use filter turn on the search capability.
  • Use remote to disabled local filter
  • Dynamic Update optionList after onSearch callback
  • Update loading when fetching data / finish
  • Use controlled value attribute

Custom search strategy

By default, the user's search input will be compared with the option's label value as a string include.
You can set filter as a custom function to customize your filter strategy.

Custom selection rendering

By default, the content of option.label or option.children will be backfilled into the selection box when the option is selected.
But you can customize the rendering of the selection box through the renderSelectedItem function
  • Select: renderSelectedItem(optionNode: object) => content: ReactNode
  • Multiple Select: renderSelectedItem(optionNode: object, { index: number, onClose: function }) => { isRenderInTag: boolean, content: ReactNode }
    • When isRenderInTag is true, content will automatically wrapped in Tag rendering (with background color and close button)
    • When isRenderInTag is false, it renders the returned content directly

Custom pop-up layer style

You can control the style of the pop-up layer through dropdownClassName, dropdownStyle
For example, when you customize the width of the pop-up layer, you can pass the width through drowndownStyle

Dynamic Modification Options

If you need to update Options dynamically, you should use controlled value

Get all attribute of selected option

By default, through onChange uou can only get value attribute of selected option.
If you need to take other attributes of the selected option, you can use onChangeWithObject Properties
At this time, the argument of onChange will be object, containing various attributes of selected option, eg: onChange({ value, label, ...rest })
Note that when onChange With Object is set to true,defaultValue/Valueit should also be object and must have value key

Create entries

You can create and select entries that do not exist in the options by setting allowCreate=true You can customize the content display when creating the label through renderCreateItem (by returning ReactNode, note that you need to customize the style) In addition, can be used with the defaultActiveFirstOption property to automatically select the first item. When you enter directly and press Enter, you can immediately create an Option

Virtualize

Turn on list virtualization when passing in virtualize to optimize performance when there are a large number of Option nodes virtualize is an object containing the following values:
  • height: Option list height value, default 300
  • width: Option list width value, default 100%
  • itemSize: The height of each line of Option, must be passed

Custom Trigger

If the default layout style of the selection box does not meet your needs, you can use triggerRender to customize the display of the selection box
The parameters of triggerRender are as follows

Custom Option Render

  • Simple customization: Pass the label property of Option or children into ReactNode, you can control the rendering of the candidates, and the content will automatically bring styles such as padding, background color, etc.
  • Complete customization: By passing in renderOptionItem, you can completely take over the rendering of the candidates in the list, and get the relevant state values from the callback input parameters. Achieve a higher degree of freedom of structural rendering
    Notice:
    1. The style passed in by props needs to be consumed on wrapper dom, otherwise it will not be able to be used normally in virtualization scenarios
    2. The styles of selected, focused, disabled, etc. state need to be added by yourself, and you can get the relative boolean value from props
    3. onMouseEnter needs to be bound on the wrapper dom, otherwise the display will be problematic when the upper and lower keyboards are operated
    4. If your custom item is Select.Option, you need to pass renderProps.onClick transparently to the onSelect prop of Option

API reference

Select Props

PropertiesInstructionsTypeDefault
allowCreateWhether to allow the user to create new entries. Needs to be used with filterbooleanfalse
arrowIconCustomize the right drop-down arrow Icon, when the showClear switch is turned on and there is currently a selected value, hover will give priority to the clear icon
supported after v1.15.0
ReactNode
autoAdjustOverflowWhether the pop-up layer automatically adjusts the direction when it is obscured (only vertical direction is supported for the time being, and the inserted parent is body)booleantrue
autoClearSearchValueAfter selecting the option, whether to automatically clear the search keywords, it will take effect when mutilple and filter are both enabled.
supported after v2.3.0
booleantrue
autoFocusWhether automatically focus when component mountbooleanfalse
classNameThe CSS class name of the wrapper elementstring
clickToHideWhen expanded, click on the selection box to automatically put away the drop-down listbooleanfalse
defaultValueOriginally selected value when component mountstring|number|array
defaultOpenWhether show dropdown when component mountedbooleanfalse
defaultActiveFirstOptionWhether to highlight the first option by default (press Enter to select directly)booleantrue
disabledWhether disabled componentbooleanfalse
dropdownClassNameClassName of the pop-up layerstring
dropdownMatchSelectWidthIs the minimum width of the drop-down menu equal to Selectbooleantrue
dropdownStyleThe inline style of the pop-up layerobject
emptyContentContent displayed when there is no result. When set to null, the drop-down list will not be displayedstringReactNode
filterWhether searchable or not, the default is false. When true is passed, it means turn on search ability, default filtering policy is whether the label matches search input
When the input type is function, the function arguments are searchInput, option. It should return true when the option meets the filtering conditions, otherwise it returns false.
falseboolean|function
getPopupContainerSpecifies the parent DOM, and the popup layer will be rendered to the DOM, you need to set 'position: relative`function(): HTMLElement() => document.body
inputPropsWhen filter is true, the additional configuration parameters of the input, please refer to the Input component for specific configurable properties (note: please do not pass in value, ref, onChange, onFocus, otherwise it will override Select related callbacks and affect component behavior)
supported after v2.2.0
object
innerTopSlotRender at the top of the pop-up layer, custom slot inside the optionListReactNode
innerBottomSlotRender at the bottom of the pop-up layer, custom slot inside the optionListReactNode
insetLabelSame to prefix, just an aliasReactNode
loadingDoes the drop-down list show the loading animationbooleanfalse
maxMaximum number of choices, effective only in multi-selection modenumber
maxTagCountIn multi-selection mode, when the option is beyond maxTag Count, the subsequent option is rendered in the form of + Nnumber
maxHeightMaximum height of optionList in the pop-up layerstringnumber
multipleWhether allow multiple selectionbooleanfalse
outerBottomSlotRendered at the bottom of the pop-up layer, custom slot level with optionListReactNode
outerTopSlotRendered at the top of the pop-up layer, custom slot level with optionList
supported after v1.6.0
optionListYou can pass Option through this property, make sure that each element in the array has label, value propertiesArray ([{value, label}])
placeholderplaceholderReactNode
positionPop-up layer position, refer to Popover·API reference·positionstring'bottomLeft'
prefixAn input helper rendered beforeReactNode
preventScrollIndicates whether the browser should scroll the document to display the newly focused element, acting on the focus method inside the component, excluding the component passed in by the userboolean
remoteWhether to turn on remote search, when remote is true, the input content will not be locally filtered and matchedbooleanfalse
renderCreateItemWhen allowCreate is true, you can customize the rendering of the creation labelfunction(inputValue: string)InputValue => 'Create' + InputValue
renderSelectedItemCustomize the rendering of selected tabs in the selection boxfunction(option)
showArrowWhether to show arrow iconbooleantrue
showClearWhether to show the clear buttonbooleanfalse
sizeSize, optional value default / small / largestring'default'
spacingSpacing between popup layer and triggernumber4
stopPropagationWhether to prevent click events on the popup layer from bubblingbooleantrue
styleInline Styleobject
suffixAn input helper rendered afterReactNode
triggerRenderCustom DOM of triggerfunction
virtualizeList virtualization, used to optimize performance in the case of a large number of nodes, composed of height, width, and itemSize
supported after v0.37.0
object
validateStatusVerification result, optional warning, error, default (only affect the style background color)string'default'
valueThe currently selected value is passed as a controlled component, used in conjunction with onchangestring|number|array
zIndexPopup layer z-indexnumber1030
onBlurCallback when blurfunction(event)
onChangeCallback function when selected optionfunction (value)
onChangeWithObjectWhether to use the other properties of the selected option as a callback. When set to true, the entry type of onchange changes from string to object: {value, label,...rest}booleanfalse
onClearCallback when click clear iconfunction
onCreateAllow Create is true and provides after the callback when creating the standby optionfunction
onDeselectCallback when selected cancelfunction (value, option)
onDropdownVisibleChangeA callback when the drop-down menu expands / collapsedfunction(visible: boolean)
onExceedCallback invoked when the number of attempts to select exceeds the max limit, effective only at multi-selectionfunction
onFocusCallback when focus selectfunction(event)
onSearchThe callback function when the content of the input box changes.function(sugInput: string)
onSelectCallback when selectedfunction (value, option)

Option Props

The label of different Option must be unique . Value allows repetition
PropertiesInstructionsTypeDefault
classNameThe CSS class name of the wrapper elementstring
disabledDisabledbooleanfalse
labelText displayed. Prioritize the label when rendering, take the child, value if not, and downgrade in turnstring|ReactNode
showTickWhether to show the Icon of tick when option selectedbooleantrue
styleInline Styleobject
valueProperty valuestring|number

OptGroup Props

PropertiesInstructionsTypeVersion
classNameThe CSS class namestringv0.31.0
labelText displayed.ReactNodev0.31.0
styleInline Styleobjectv0.31.0

Method()

MethodInstructionsVersion
closeManually close dropdown listv0.34.0
clearInputManually clear value of inputv1.18.0
deselectAllManually clear selected optionsv1.18.0
focusManually focus selectv1.11.0
openManually open dropdown listv0.34.0
selectAllManually select all optionsv1.18.0

Accessibility

ARIA

  • The role of the Select trigger is combobox, the role of the popup layer is listbox, and the role of the option is option
  • Select trigger has aria-haspopup, aria-expanded, and aria-controls properties, indicating the relationship between trigger and popup layer
  • When multiple selections are made, listbox aria-multiselectable is true, indicating that multiple selections are currently available
  • aria-selected is true when Option is selected; aria-disabled is true when Option is disabled
  • The attribute aria-activedescendant ensures that the currently selected option is recognized when the narration is spoken(for more information, please refer to Managing Focus in Composites Using aria-activedescendant)

Keyboard and Focus

Select without Filter:
  • After Select is focused, keyboard users can open the dropdown menu with the Up Arrow or Down Arrow or Enter keys and automatically focus on the first option in the dropdown menu (defaultActiveFirstOption defaults to true)
  • When the dropdown menu is open:
    • Use Esc key or Tab key to close the menu
    • Use Up Arrow or Down Arrow to toggle options
    • The focused option can be selected with the Enter key and the panel is collapsed
  • When the focus is on the dropdown menu and the user uses an innerBottomSlot or outerBottomSlot attribute with a custom slot with an interactive element:
    • You can use the Tab key to switch to these interactive elements
    • When the focus is on the first interactive element of the custom slot, use Shift + Tab to return the focus to the Select box
Select with Filter function:
  • When Select is focused, keyboard users can open dropdown menus with Up Arrow or Down Arrow or Enter keys. At this point, the focus is still on the Select box, the user can enter content, and can also use the up arrow or down arrow to switch options
  • When the dropdown menu is open: the keyboard interaction is the same as Select without the Filter function
  • When the focus is on the Select box, and the user uses an innerBottomSlot or outerBottomSlot property with a custom slot with an interactive element:
    • You can use the Tab key to switch to these interactive elements
    • When the focus is on the first interactive element of the custom slot, use Shift + Tab to return the focus to the Select box

Content Guidelines

  • Selector trigger
    • Describe in 1-3 words the input that the user needs to make
    • Use statement writing conventions (first letter uppercase, rest lowercase)
    • Avoid punctuation and prepositions ("the", "an", "a")
    • Labels need to be independent statements. Don't let the label be the first half of the statement and the option the second half of the statement.
    • Use descriptive sentences, not indicative ones. Help text is available under the select box if the option needs more explanation.
  • Selector options
    • If there is no default option, use "Select" as placeholder copy
    • Options should be in alphabetical order or other logical order to make it easier for users to find options
    • Use statement writing conventions (first letter uppercase, rest lowercase), avoid commas and semicolons at the end of sentences
    • Clearly articulate the purpose of the choice indicated by the option

Design Tokens

FAQ

  • Searchable Select, using remote data to dynamically update the optionList, why sometimes there is no data before the asynchronous request is completed??
    Please check whether remote={true} is set. If remote is not set, the input value of the input box will be compared with the current optionList by default. If there is no match, no data will be displayed.
    You can turn off matching filtering on the current local data by setting remote to true.
  • Use jsx to declare Option, label is the content after i18n, fail to re-render after switching locale When the children jsx method declares Options, because it is ReactNode, it is impossible to use deepEqual to compare whether the content is updated (excessive performance consumption), so the key of children ReactNode will be collected. When the key is unchanged, it is considered that Options have not occurred. Changes will not go through the process of re-collecting data. You can also use locale as part of the Option key.
    The problem can also be solved by using optionList to pass in. Because the key is relatively limited for the object form, isEqual is used inside Select to determine whether there is a change
  • Use jsx to declare Option, and fail to re-render after dynamically switching the disabled attribute
    The reason is the same as above, you can set a different key value for Option again, or use optionList to declare candidate options
  • Will Select automatically limit the width of the drop-down menu?
    MinWidth will be given, but width will not be written dead. If necessary, you can add it yourself through dropdownStyle.
  • After setting allowCreate, dynamically updating optionList or children does not take effect
    allowCreate is mainly used for locally created scenarios. When this item is turned on, it is equivalent to forcibly taking over optionList/children, and will no longer respond to external updates to these two types of values. Otherwise, how the currently created options are combined with the latest props.optionList, and whether the strategy is overwritten or merged depends largely on the business scenario logic, and it is inappropriate to force presets by the component layer.
  • Why Semi's Select requires that the label must be unique, but not the value?
    Unique label and repeated value are more common in daily use. For example, a selector that selects the company id based on the app name, value is the company id corresponding to the app, and label is the name of the app. We don't recommend showing the user a duplicate label option, but if you're sure you need to, you can bypass this restriction when you pass a ReactNode type to the label.
  • Why is the blur event not fired after a radio selection option?
    Before V2.17.0, after Select radio is selected, the blur event of Select will be triggered. After V2.17.0, Select has added A11y support, which will not trigger Select's blur event. In single-selection selection, the Select floating layer is closed, and the focus is still on the trigger (at this time, the Select floating layer can be opened again by pressing the Enter key) No matter single selection or multiple selection, press Esc, only the Select floating layer is closed, and the trigger keeps the focus (the Select floating layer can be opened again by pressing the Enter key at this time)

© 2021 - 2022 Semi Design. All rights reserved.

京ICP备19058139号-13浙公网安备 33011002016131号

Designed & Developed with love by Douyin FE & MED