Select

Select component to select value from options.

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).

Examples

Basic Usage.

expand codeexpand code
import { Select } from 'antd';

const { Option } = Select;

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <div>
    <Select defaultValue="lucy" style={{ width: 120 }} onChange={handleChange}>
      <Option value="jack">Jack</Option>
      <Option value="lucy">Lucy</Option>
      <Option value="disabled" disabled>
        Disabled
      </Option>
      <Option value="Yiminghe">yiminghe</Option>
    </Select>
    <Select defaultValue="lucy" style={{ width: 120 }} disabled>
      <Option value="lucy">Lucy</Option>
    </Select>
    <Select defaultValue="lucy" style={{ width: 120 }} loading>
      <Option value="lucy">Lucy</Option>
    </Select>
  </div>,
  mountNode,
);

Multiple selection, selecting from existing items.

expand codeexpand code
import { Select } from 'antd';

const { Option } = Select;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select
    mode="multiple"
    style={{ width: '100%' }}
    placeholder="Please select"
    defaultValue={['a10', 'c12']}
    onChange={handleChange}
  >
    {children}
  </Select>,
  mountNode,
);

Select with tags, transform input to tag (scroll the menu)

expand codeexpand code
import { Select } from 'antd';

const { Option } = Select;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select mode="tags" style={{ width: '100%' }} placeholder="Tags Mode" onChange={handleChange}>
    {children}
  </Select>,
  mountNode,
);

Using OptGroup to group the options.

expand codeexpand code
import { Select } from 'antd';

const { Option, OptGroup } = Select;

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select defaultValue="lucy" style={{ width: 200 }} onChange={handleChange}>
    <OptGroup label="Manager">
      <Option value="jack">Jack</Option>
      <Option value="lucy">Lucy</Option>
    </OptGroup>
    <OptGroup label="Engineer">
      <Option value="Yiminghe">yiminghe</Option>
    </OptGroup>
  </Select>,
  mountNode,
);

Try to copy Lucy,Jack to the input. Only available in tags and multiple mode.

expand codeexpand code
import { Select } from 'antd';

const { Option } = Select;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select mode="tags" style={{ width: '100%' }} onChange={handleChange} tokenSeparators={[',']}>
    {children}
  </Select>,
  mountNode,
);

Customize the dropdown menu via dropdownRender. The selection will be closed if click dropdownRender area, you can prevent it by wrapping onMouseDown={e => e.preventDefault()} (see more at #13448).

expand codeexpand code
import { Select, Icon, Divider } from 'antd';

const { Option } = Select;

let index = 0;

class App extends React.Component {
  state = {
    items: ['jack', 'lucy'],
  };

  addItem = () => {
    console.log('addItem');
    const { items } = this.state;
    this.setState({
      items: [...items, `New item ${index++}`],
    });
  };

  render() {
    const { items } = this.state;
    return (
      <Select
        style={{ width: 240 }}
        placeholder="custom dropdown render"
        dropdownRender={menu => (
          <div>
            {menu}
            <Divider style={{ margin: '4px 0' }} />
            <div
              style={{ padding: '4px 8px', cursor: 'pointer' }}
              onMouseDown={e => e.preventDefault()}
              onClick={this.addItem}
            >
              <Icon type="plus" /> Add item
            </div>
          </div>
        )}
      >
        {items.map(item => (
          <Option key={item}>{item}</Option>
        ))}
      </Select>
    );
  }
}

ReactDOM.render(<App />, mountNode);




The height of the input field for the select defaults to 32px. If size is set to large, the height will be 40px, and if set to small, 24px.

expand codeexpand code
import { Select, Radio } from 'antd';

const { Option } = Select;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

function handleChange(value) {
  console.log(`Selected: ${value}`);
}

class SelectSizesDemo extends React.Component {
  state = {
    size: 'default',
  };

  handleSizeChange = e => {
    this.setState({ size: e.target.value });
  };

  render() {
    const { size } = this.state;
    return (
      <div>
        <Radio.Group value={size} onChange={this.handleSizeChange}>
          <Radio.Button value="large">Large</Radio.Button>
          <Radio.Button value="default">Default</Radio.Button>
          <Radio.Button value="small">Small</Radio.Button>
        </Radio.Group>
        <br />
        <br />
        <Select size={size} defaultValue="a1" onChange={handleChange} style={{ width: 200 }}>
          {children}
        </Select>
        <br />
        <Select
          mode="multiple"
          size={size}
          placeholder="Please select"
          defaultValue={['a10', 'c12']}
          onChange={handleChange}
          style={{ width: '100%' }}
        >
          {children}
        </Select>
        <br />
        <Select
          mode="tags"
          size={size}
          placeholder="Please select"
          defaultValue={['a10', 'c12']}
          onChange={handleChange}
          style={{ width: '100%' }}
        >
          {children}
        </Select>
      </div>
    );
  }
}

ReactDOM.render(<SelectSizesDemo />, mountNode);
.code-box-demo .ant-select {
  margin: 0 8px 10px 0;
}

#components-select-demo-search-box .code-box-demo .ant-select {
  margin: 0;
}

Spacified the prop name of Option which will be rendered in select box.

expand codeexpand code
import { Select } from 'antd';

const { Option } = Select;

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select
    mode="multiple"
    style={{ width: '100%' }}
    placeholder="select one country"
    defaultValue={['china']}
    onChange={handleChange}
    optionLabelProp="label"
  >
    <Option value="china" label="China">
      <span role="img" aria-label="China">
        🇨🇳
      </span>
      China (中国)
    </Option>
    <Option value="usa" label="USA">
      <span role="img" aria-label="USA">
        🇺🇸
      </span>
      USA (美国)
    </Option>
    <Option value="japan" label="Japan">
      <span role="img" aria-label="Japan">
        🇯🇵
      </span>
      Japan (日本)
    </Option>
    <Option value="korea" label="Korea">
      <span role="img" aria-label="Korea">
        🇰🇷
      </span>
      Korea (韩国)
    </Option>
  </Select>,
  mountNode,
);
span[role="img"] {
  margin-right: 6px;
}

Coordinating the selection of provinces and cities is a common use case and demonstrates how selection can be coordinated.

Using the Cascader component is strongly recommended instead as it is more flexible and capable.

expand codeexpand code
import { Select } from 'antd';

const { Option } = Select;
const provinceData = ['Zhejiang', 'Jiangsu'];
const cityData = {
  Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
  Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
};

class App extends React.Component {
  state = {
    cities: cityData[provinceData[0]],
    secondCity: cityData[provinceData[0]][0],
  };

  handleProvinceChange = value => {
    this.setState({
      cities: cityData[value],
      secondCity: cityData[value][0],
    });
  };

  onSecondCityChange = value => {
    this.setState({
      secondCity: value,
    });
  };

  render() {
    const { cities } = this.state;
    return (
      <div>
        <Select
          defaultValue={provinceData[0]}
          style={{ width: 120 }}
          onChange={this.handleProvinceChange}
        >
          {provinceData.map(province => (
            <Option key={province}>{province}</Option>
          ))}
        </Select>
        <Select
          style={{ width: 120 }}
          value={this.state.secondCity}
          onChange={this.onSecondCityChange}
        >
          {cities.map(city => (
            <Option key={city}>{city}</Option>
          ))}
        </Select>
      </div>
    );
  }
}

ReactDOM.render(<App />, mountNode);

As a default behavior, the onChange callback can only get the value of the selected item. The labelInValue prop can be used to get the label property of the selected item.

The label of the selected item will be packed as an object for passing to the onChange callback.

expand codeexpand code
import { Select } from 'antd';

const { Option } = Select;

function handleChange(value) {
  console.log(value); // { key: "lucy", label: "Lucy (101)" }
}

ReactDOM.render(
  <Select
    labelInValue
    defaultValue={{ key: 'lucy' }}
    style={{ width: 120 }}
    onChange={handleChange}
  >
    <Option value="jack">Jack (100)</Option>
    <Option value="lucy">Lucy (101)</Option>
  </Select>,
  mountNode,
);

A complete multiple select sample with remote search, debounce fetch, ajax callback order flow, and loading state.

expand codeexpand code
import { Select, Spin } from 'antd';
import debounce from 'lodash/debounce';

const { Option } = Select;

class UserRemoteSelect extends React.Component {
  constructor(props) {
    super(props);
    this.lastFetchId = 0;
    this.fetchUser = debounce(this.fetchUser, 800);
  }

  state = {
    data: [],
    value: [],
    fetching: false,
  };

  fetchUser = value => {
    console.log('fetching user', value);
    this.lastFetchId += 1;
    const fetchId = this.lastFetchId;
    this.setState({ data: [], fetching: true });
    fetch('https://randomuser.me/api/?results=5')
      .then(response => response.json())
      .then(body => {
        if (fetchId !== this.lastFetchId) {
          // for fetch callback order
          return;
        }
        const data = body.results.map(user => ({
          text: `${user.name.first} ${user.name.last}`,
          value: user.login.username,
        }));
        this.setState({ data, fetching: false });
      });
  };

  handleChange = value => {
    this.setState({
      value,
      data: [],
      fetching: false,
    });
  };

  render() {
    const { fetching, data, value } = this.state;
    return (
      <Select
        mode="multiple"
        labelInValue
        value={value}
        placeholder="Select users"
        notFoundContent={fetching ? <Spin size="small" /> : null}
        filterOption={false}
        onSearch={this.fetchUser}
        onChange={this.handleChange}
        style={{ width: '100%' }}
      >
        {data.map(d => (
          <Option key={d.value}>{d.text}</Option>
        ))}
      </Select>
    );
  }
}

ReactDOM.render(<UserRemoteSelect />, mountNode);

Hide already selected options in the dropdown.

expand codeexpand code
import { Select } from 'antd';

const OPTIONS = ['Apples', 'Nails', 'Bananas', 'Helicopters'];

class SelectWithHiddenSelectedOptions extends React.Component {
  state = {
    selectedItems: [],
  };

  handleChange = selectedItems => {
    this.setState({ selectedItems });
  };

  render() {
    const { selectedItems } = this.state;
    const filteredOptions = OPTIONS.filter(o => !selectedItems.includes(o));
    return (
      <Select
        mode="multiple"
        placeholder="Inserted are removed"
        value={selectedItems}
        onChange={this.handleChange}
        style={{ width: '100%' }}
      >
        {filteredOptions.map(item => (
          <Select.Option key={item} value={item}>
            {item}
          </Select.Option>
        ))}
      </Select>
    );
  }
}

ReactDOM.render(<SelectWithHiddenSelectedOptions />, mountNode);

API#

<select>
  <option value="lucy">lucy</option>
</select>

Select props#

PropertyDescriptionTypeDefaultVersion
allowClearShow clear button.booleanfalse
autoClearSearchValueWhether the current search will be cleared on selecting an item. Only applies when mode is set to multiple or tags.booleantrue3.10.0
autoFocusGet focus by defaultbooleanfalse
defaultActiveFirstOptionWhether active first option by defaultbooleantrue
defaultValueInitial selected option.string|string[]
number|number[]
LabeledValue|LabeledValue[]
-
disabledWhether disabled selectbooleanfalse
dropdownClassNameclassName of dropdown menustring-
dropdownMatchSelectWidthWhether dropdown's width is same with select.booleantrue
dropdownRenderCustomize dropdown content(menuNode: ReactNode, props) => ReactNode-3.11.0
dropdownStylestyle of dropdown menuobject-
dropdownMenuStyleadditional style applied to dropdown menuobject-
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 excluded.boolean or function(inputValue, option)true
firstActiveValueValue of action option by defaultstring|string[]-
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 {key: string, label: ReactNode}booleanfalse
maxTagCountMax tag count to shownumber-
maxTagTextLengthMax tag text length to shownumber-3.18.0
maxTagPlaceholderPlaceholder for not showing tagsReactNode/function(omittedValues)-
modeSet mode of Select'default' | 'multiple' | 'tags''default'
notFoundContentSpecify content to show when no result matches..string'Not Found'
optionFilterPropWhich prop value of option will be used for filter if filterOption is truestringvalue
optionLabelPropWhich prop value of option will render as content of select. Examplestringvalue for combobox, children for other modes
placeholderPlaceholder of selectstring|ReactNode-
showArrowWhether to show the drop-down arrowbooleantrue3.2.1
showSearchWhether show search input in single mode.booleanfalse
sizeSize of Select input. default large smallstringdefault
suffixIconThe custom suffix iconReactNode-3.10.0
removeIconThe custom remove iconReactNode-3.11.0
clearIconThe custom clear iconReactNode-3.11.0
menuItemSelectedIconThe custom menuItemSelected icon with multiple optionsReactNode-3.11.0
tokenSeparatorsSeparator used to tokenize on tag/multiple modestring[]
valueCurrent selected option.string|string[]\
number|number[]\
LabeledValue|LabeledValue[]
-
onBlurCalled when blurfunction-
onChangeCalled when select an option or input value change, or value of input is changed in combobox modefunction(value, option:Option/Array<Option>)-
onDeselectCalled when a option is deselected, param is the selected option's value. Only called for multiple or tags, effective in multiple or tags mode only.function(string|number|LabeledValue)-
onFocusCalled when focusfunction-
onInputKeyDownCalled when key pressedfunction-3.1.0
onMouseEnterCalled when mouse enterfunction-
onMouseLeaveCalled when mouse leavefunction-
onPopupScrollCalled when dropdown scrollsfunction-
onSearchCallback function that is fired when input changed.function(value: string)
onSelectCalled when a option is selected, the params are option's value (or key) and option instance.function(string|number|LabeledValue, option:Option)-
defaultOpenInitial open state of dropdownboolean-3.9.3
openControlled open state of dropdownboolean-3.9.0
onDropdownVisibleChangeCall when dropdown open (Supported after version 3.9.0)function(open)-3.9.0
loadingindicate loading stateBooleanfalse3.11.0

Select Methods#

NameDescriptionVersion
blur()Remove focus
focus()Get focus

Option props#

PropertyDescriptionTypeDefaultVersion
disabledDisable this optionbooleanfalse
keySame usage as value. If React request you to set this property, you can set it to value of option, and then omit value property.string
titletitle of Select after select this Optionstring-
valuedefault to filter with this propertystring|number-
classNameadditional class to optionstring-3.10.1

OptGroup props#

PropertyDescriptionTypeDefaultVersion
keystring-
labelGroup labelstring|React.Element-

FAQ#

The dropdown is closed when click dropdownRender area?#

See the instruction in dropdownRender example.

RadioSlider