Select

Select component to select value from options.

When To Use#

  • A dropdown menu for choosing, an elegant alternative to the native select component.

  • Radio is a better solution when options amount is too little (less than 5).

Examples

Basic Usage.

expand codeexpand code
import { Select } from 'antd';
const Option = Select.Option;

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 }} allowClear disabled>
      <Option value="lucy">Lucy</Option>
    </Select>
  </div>
, mountNode);

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

expand codeexpand code
import { Select } from 'antd';
const Option = Select.Option;

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.Option;

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





The height of the inpub field for the select defaults to 28px. If size is set to large, the height will be 32px, and if set to small, 22px.

expand codeexpand code
import { Select, Radio } from 'antd';
const Option = Select.Option;

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="combobox"
          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;
}

Multiple selection, selecting from existing items (scroll the menu).

expand codeexpand code
import { Select } from 'antd';
const Option = Select.Option;

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

Automatic completion of select input.

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

expand codeexpand code
import { Select } from 'antd';
const Option = Select.Option;

class App extends React.Component {
  state = {
    options: [],
  }
  handleChange = (value) => {
    let options;
    if (!value || value.indexOf('@') >= 0) {
      options = [];
    } else {
      options = ['gmail.com', '163.com', 'qq.com'].map((domain) => {
        const email = `${value}@${domain}`;
        return <Option key={email}>{email}</Option>;
      });
    }
    this.setState({ options });
  }
  render() {
    // filterOption needs to be false,as the value is dynamically generated
    return (
      <Select
        mode="combobox"
        style={{ width: 200 }}
        onChange={this.handleChange}
        filterOption={false}
        placeholder="Enter the account name"
      >
        {this.state.options}
      </Select>
    );
  }
}

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

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.Option;

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 provinceOptions = provinceData.map(province => <Option key={province}>{province}</Option>);
    const cityOptions = this.state.cities.map(city => <Option key={city}>{city}</Option>);
    return (
      <div>
        <Select defaultValue={provinceData[0]} style={{ width: 90 }} onChange={this.handleProvinceChange}>
          {provinceOptions}
        </Select>
        <Select value={this.state.secondCity} style={{ width: 90 }} onChange={this.onSecondCityChange}>
          {cityOptions}
        </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.Option;

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.Option;

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({ 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,
          fetching: false,
        }));
        this.setState({ data });
      });
  }
  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);

API#

<Select>
  <Option value="lucy">lucy</Option>
</Select>

Select props#

PropertyDescriptionTypeDefault
valueCurrent selected option.string|string[]-
defaultValueInitial selected option.string|string[]-
modeSet mode of Select (Support after 2.9)'multiple' | 'tags' | 'combobox'-
multipleAllow multiple select (Deprecated after 2.9, use mode instead)booleanfalse
tagsWhen tagging is enabled the user can select from pre-existing options or create a new tag by picking the first choice, which is what the user has typed into the search box so far. (Deprecated after 2.9, use mode instead)booleanfalse
comboboxEnable combobox mode (can not set multiple at the same time). (Deprecated after 2.9, use mode instead)booleanfalse
allowClearShow clear button.booleanfalse
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
onSelectCalled when a option is selected, the params are option's value (or key) and option instance.function(value, option)-
onDeselectCalled when a option is deselected, the params are option's value (or key) . only called for multiple or tags, effective in multiple or tags mode only.function(value)-
onChangeCalled when select an option or input value change, or value of input is changed in combobox modefunction(value, label)-
onSearchCallback function that is fired when input changed.function(value: string)
onBlurCalled when blurfunction-
onFocusCalled when focusfunction-
placeholderPlaceholder of selectstring|ReactNode-
notFoundContentSpecify content to show when no result matches..string'Not Found'
dropdownMatchSelectWidthWhether dropdown's with is same with select.booleantrue
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.stringchildren
sizeSize of Select input. large smallstringdefault
showSearchWhether show search input in single mode.booleanfalse
disabledWhether disabled selectbooleanfalse
defaultActiveFirstOptionWhether active first option by defaultbooleantrue
dropdownStylestyle of dropdown menuobject-
dropdownClassNameclassName of dropdown menustring-
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
tokenSeparatorsSeparator used to tokenize on tag/multiple modestring[]
firstActiveValueValue of action option by defaultstring|string[]-

Option props#

PropertyDescriptionTypeDefault
disabledDisable this optionbooleanfalse
valuedefault to filter with this propertystring-
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-

OptGroup props#

PropertyDescriptionTypeDefault
labelGroup labelstring|React.Element-
keystring-