Back to Ant Design

Select

components/select/index.en-US.md

6.3.715.9 KB
Original Source

When To Use

  • A dropdown menu for displaying choices - an elegant alternative to the native <select> element.
  • Utilizing Radio is recommended when there are fewer total options (less than 5).
  • You probably need AutoComplete if you're looking for an input box that can be typed or selected.

Examples

<!-- prettier-ignore -->

<code src="./demo/basic.tsx">Basic Usage</code> <code src="./demo/search.tsx">Select with search field</code> <code src="./demo/search-filter-option.tsx">Custom Search</code> <code src="./demo/search-multi-field.tsx">Multi field search</code> <code src="./demo/multiple.tsx">multiple selection</code> <code src="./demo/size.tsx">Sizes</code> <code src="./demo/option-render.tsx">Custom dropdown options</code> <code src="./demo/search-sort.tsx">Search with sort</code> <code src="./demo/tags.tsx">Tags</code> <code src="./demo/optgroup.tsx">Option Group</code> <code src="./demo/coordinate.tsx">coordinate</code> <code src="./demo/search-box.tsx">Search Box</code> <code src="./demo/label-in-value.tsx">Get value of selected item</code> <code src="./demo/automatic-tokenization.tsx">Automatic tokenization</code> <code src="./demo/select-users.tsx">Search and Select Users</code> <code src="./demo/suffix.tsx" version="5.22.0">Prefix and Suffix</code> <code src="./demo/custom-dropdown-menu.tsx">Custom dropdown</code> <code src="./demo/hide-selected.tsx">Hide Already Selected</code> <code src="./demo/variant.tsx" version="5.13.0">Variants</code> <code src="./demo/filled-debug.tsx" debug>Filled debug</code> <code src="./demo/custom-tag-render.tsx">Custom Tag Render</code> <code src="./demo/custom-label-render.tsx">Custom Selected Label Render</code> <code src="./demo/responsive.tsx">Responsive maxTagCount</code> <code src="./demo/big-data.tsx">Big Data</code> <code src="./demo/status.tsx">Status</code> <code src="./demo/placement.tsx">Placement</code> <code src="./demo/placement-debug.tsx" debug>Dynamic Height</code> <code src="./demo/debug.tsx" debug>For Debug</code> <code src="./demo/render-panel.tsx" debug>_InternalPanelDoNotUseOrYouWillBeFired</code> <code src="./demo/option-label-center.tsx" debug>Options label Centered</code> <code src="./demo/debug-flip-shift.tsx" iframe="200" debug>Flip + Shift</code> <code src="./demo/component-token.tsx" debug>Component Token</code> <code src="./demo/maxCount.tsx" version="5.13.0">Max Count</code> <code src="./demo/style-class.tsx" version="6.0.0">Custom semantic dom styling</code>

API

Common props ref:Common props

Select props

PropertyDescriptionTypeDefaultVersion
allowClearCustomize clear iconboolean | { clearIcon?: ReactNode }false5.8.0: Support object type
autoClearSearchValueWhether the current search will be cleared on selecting an item. Only applies when mode is set to multiple or tagsbooleantrue
borderedWhether has border style, please use variant insteadbooleantrue-
classNamesCustomize class for each semantic structure inside the Select component. Supports object or function.Record<SemanticDOM, string> | (info: { props })=> Record<SemanticDOM, string>-
defaultActiveFirstOptionWhether active first option by defaultbooleantrue
defaultOpenInitial open state of dropdownboolean-
defaultValueInitial selected optionstring | string[] |
number | number[] |
LabeledValue | LabeledValue[]-
disabledWhether disabled selectbooleanfalse
dropdownClassNameThe className of dropdown menu, please use classNames.popup.root insteadstring--
dropdownMatchSelectWidthDetermine whether the popup menu and the select input are the same width, please use popupMatchSelectWidth insteadboolean | numbertrue-
popupClassNameThe className of dropdown menu, use classNames.popup.root insteadstring-4.23.0
popupMatchSelectWidthDetermine whether the popup menu and the select input are the same width. Default set min-width same as input. Will ignore when value less than select width. false will disable virtual scrollboolean | numbertrue5.5.0
dropdownRenderCustomize dropdown content, use popupRender instead(originNode: ReactNode) => ReactNode-
popupRenderCustomize dropdown content(originNode: ReactNode) => ReactNode-5.25.0
dropdownStyleThe style of dropdown menu, use styles.popup.root insteadCSSProperties-
fieldNamesCustomize node label, value, options,groupLabel field nameobject{ label: label, value: value, options: options, groupLabel: label }4.17.0 (groupLabel added in 5.6.0)
filterOptionIf true, filter options by input, if function, filter options against it. The function will receive two arguments, inputValue and option, if the function returns true, the option will be included in the filtered set; Otherwise, it will be excludedboolean | function(inputValue, option)true
filterSortSort function for search options sorting, see Array.sort's compareFunction(optionA: Option, optionB: Option, info: { searchValue: string }) => number-searchValue: 5.19.0
getPopupContainerParent Node which the selector should be rendered to. Default to body. When position issues happen, try to modify it into scrollable content and position it relative. Examplefunction(triggerNode)() => document.body
labelInValueWhether to embed label in value, turn the format of value from string to { value: string, label: ReactNode }booleanfalse
listHeightConfig popup heightnumber256
loadingIndicate loading statebooleanfalse
maxCountThe max number of items can be selected, only applies when mode is multiple or tagsnumber-5.13.0
maxTagCountMax tag count to show. responsive will cost render performancenumber | responsive-responsive: 4.10
maxTagPlaceholderPlaceholder for not showing tagsReactNode | function(omittedValues)-
maxTagTextLengthMax tag text length to shownumber-
menuItemSelectedIconThe custom menuItemSelected icon with multiple optionsReactNode-
modeSet mode of Selectmultiple | tags-
notFoundContentSpecify content to show when no result matchesReactNodeNot Found
openControlled open state of dropdownboolean-
optionFilterPropDeprecated, see showSearch.optionFilterProp
optionLabelPropWhich prop value of option will render as content of select. Examplestringchildren
optionsSelect options. Will get better perf than jsx definition{ label, value }[]-
optionRenderCustomize the rendering dropdown options(option: FlattenOptionData<BaseOptionType> , info: { index: number }) => React.ReactNode-5.11.0
placeholderPlaceholder of selectReactNode-
placementThe position where the selection box pops upbottomLeft bottomRight topLeft topRightbottomLeft
prefixThe custom prefixReactNode-5.22.0
removeIconThe custom remove iconReactNode-
searchValueThe current input "search" textstring-
showArrowWhether to show the arrow icon, please use suffixIcon={null} insteadbooleantrue-
showSearchWhether select is searchableboolean | Objectsingle: false, multiple: true
sizeSize of Select inputlarge | medium | smallmedium
statusSet validation status'error' | 'warning'-4.19.0
stylesCustomize inline style for each semantic structure inside the Select component. Supports object or function.Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties>-
suffixIconThe custom suffix icon. Customize icon will not response click open to avoid icon designed to do other interactive. You can use pointer-events: none style to bypassReactNode<DownOutlined />
tagRenderCustomize tag render, only applies when mode is set to multiple or tags(props) => ReactNode-
labelRenderCustomize selected label render (LabelInValueType definition see LabelInValueType)(props: LabelInValueType) => ReactNode-5.15.0
tokenSeparatorsSeparator used to tokenize, only applies when mode="tags"string[]-
valueCurrent selected option (considered as a immutable array)string | string[] |
number | number[] |
LabeledValue | LabeledValue[]-
variantVariants of selectoroutlined | borderless | filled | underlinedoutlined5.13.0 | underlined: 5.24.0
virtualDisable virtual scroll when set to falsebooleantrue4.1.0
onActiveCalled when keyboard or mouse interaction occursfunction(value: string | number | LabeledValue)-
onBlurCalled when blurfunction-
onChangeCalled when select an option or input value changefunction(value, option:Option | Array<Option>)-
onClearCalled when clearfunction-4.6.0
onDeselectCalled when an option is deselected, param is the selected option's value. Only called for multiple or tags, effective in multiple or tags mode onlyfunction(value: string | number | LabeledValue)-
onDropdownVisibleChangeCalled when dropdown open, use onOpenChange instead(open: boolean) => void-
onOpenChangeCalled when dropdown open(open: boolean) => void-
onFocusCalled when focus(event: FocusEvent) => void-
onInputKeyDownCalled when key pressed(event: KeyboardEvent) => void-
onPopupScrollCalled when dropdown scrolls(event: UIEvent) => void-
onSearchCallback function that is fired when input changedfunction(value: string)-
onSelectCalled when an option is selected, the params are option's value (or key) and option instancefunction(value: string | number | LabeledValue, option: Option)-

Note, if you find that the drop-down menu scrolls with the page, or you need to trigger Select in other popup layers, please try to use getPopupContainer={triggerNode => triggerNode.parentElement} to fix the drop-down popup rendering node in the parent element of the trigger .

showSearch

PropertyDescriptionTypeDefaultVersion
autoClearSearchValueWhether the current search will be cleared on selecting an item. Only applies when mode is set to multiple or tagsbooleantrue
filterOptionIf true, filter options by input, if function, filter options against it. The function will receive two arguments, inputValue and option, if the function returns true, the option will be included in the filtered set; Otherwise, it will be excludedboolean | function(inputValue, option)true
filterSortSort function for search options sorting, see Array.sort's compareFunction(optionA: Option, optionB: Option, info: { searchValue: string }) => number-searchValue: 5.19.0
optionFilterPropWhich prop value of option will be used for filter if filterOption is true.
If options is set, it should be set to label.
When a string[] is provided, multiple fields are searched using OR matching.string | string[]valuestring[]: 6.1.0
searchValueThe current input "search" textstring-
onSearchCallback function that is fired when input changedfunction(value: string)-

Select Methods

NameDescriptionVersion
blur()Remove focus
focus()Get focus

Option props

PropertyDescriptionTypeDefaultVersion
classNameThe additional class to optionstring-
disabledDisable this optionbooleanfalse
titletitle attribute of Select Optionstring-
valueDefault to filter with this propertystring | number-

OptGroup props

PropertyDescriptionTypeDefaultVersion
keyGroup keystring-
labelGroup labelReact.ReactNode-
classNameThe additional class to optionstring-
titletitle attribute of Select Optionstring-

Semantic DOM

<code src="./demo/_semantic.tsx" simplify="true"></code>

Design Token

<ComponentTokenTable component="Select"></ComponentTokenTable>

FAQ

Why sometimes search will show 2 same option when in tags mode? {#faq-tags-mode-duplicate}

It's caused by option with different label and value. You can use optionFilterProp="label" to change filter logic instead.

When I click elements in popupRender, the select dropdown will not be closed? {#faq-popup-not-close}

You can control it by open prop: codesandbox.

I don't want dropdown close when click inside popupRender? {#faq-popup-keep-open}

Select will close when it lose focus. You can prevent event to handle this:

tsx
<Select
  popupRender={() => (
    <div
      onMouseDown={(e) => {
        e.preventDefault();
        e.stopPropagation();
      }}
    >
      Some Content
    </div>
  )}
/>

Why sometimes customize Option cause scroll break? {#faq-custom-option-scroll}

Virtual scroll internal set item height as 24px. You need to adjust listItemHeight when your option height is less and listHeight config list container height:

tsx
<Select listItemHeight={10} listHeight={250} />

Note: listItemHeight and listHeight are internal props. Please only modify when necessary.

Why a11y test report missing aria- props? {#faq-aria-attribute}

Select only create a11y auxiliary node when operating on. Please open Select and retry. For aria-label & aria-labelledby miss warning, please add related prop to Select with your own requirement.

Default virtual scrolling will create a mock element to simulate an accessible binding. If a screen reader needs to fully access the entire list, you can set virtual={false} to disable virtual scrolling and the accessibility option will be bound to the actual element.

Custom tags generated using tagRender will pop up a drop-down box when clicked to close {#faq-tagrender-dropdown}

If you don't want a drop-down menu to appear automatically after clicking on an element (such as a close icon), you can prevent the MouseDown event from propagating on it.

tsx
<Select
  tagRender={(props) => {
    const { closable, label, onClose } = props;
    return (
      <span className="border">
        {label}
        {closable ? (
          <span
            onMouseDown={(e) => e.stopPropagation()}
            onClick={onClose}
            className="cursor-pointer"
          >
            ❎
          </span>
        ) : null}
      </span>
    );
  }}
/>