logoAnt Design

⌘ K
  • Design
  • Development
  • Components
  • Blog
  • Resources
5.3.2
  • Components Overview
  • General
    • Button
    • Icon
    • Typography
  • Layout
    • Divider
    • Grid
    • Layout
    • Space
  • Navigation
    • Anchor
    • Breadcrumb
    • Dropdown
    • Menu
    • Pagination
    • Steps
  • Data Entry
    • AutoComplete
    • Cascader
    • Checkbox
    • DatePicker
    • Form
    • Input
    • InputNumber
    • Mentions
    • Radio
    • Rate
    • Select
    • Slider
    • Switch
    • TimePicker
    • Transfer
    • TreeSelect
    • Upload
  • Data Display
    • Avatar
    • Badge
    • Calendar
    • Card
    • Carousel
    • Collapse
    • Descriptions
    • Empty
    • Image
    • List
    • Popover
    • QRCode
    • Segmented
    • Statistic
    • Table
    • Tabs
    • Tag
    • Timeline
    • Tooltip
    • Tour
    • Tree
  • Feedback
    • Alert
    • Drawer
    • Message
    • Modal
    • Notification
    • Popconfirm
    • Progress
    • Result
    • Skeleton
    • Spin
  • Other
    • Affix
    • App
    • ConfigProvider
    • FloatButton
    • Watermark
When To Use
Examples
Basic Usage
Select with search field
multiple selection
Sizes
Custom selection render
Search with sort
Tags
Option Group
coordinate
Search Box
Get value of selected item
Automatic tokenization
Search and Select Users
Custom dropdown
Hide Already Selected
Bordered-less
Custom Tag Render
Responsive maxTagCount
Big Data
Status
Placement
API
Select props
Select Methods
Option props
OptGroup props
FAQ
Why sometime search will show 2 same option when in tags mode?
When I click elements in dropdownRender, the select dropdown will not be closed?
I don't want dropdown close when click inside dropdownRender?
Why sometime customize Option cause scroll break?
Why a11y test report missing aria- props?

Select

RateSlider

Resources

Ant Design Charts
Ant Design Pro
Ant Design Pro Components
Ant Design Mobile
Ant Design Mini
Ant Design Landing-Landing Templates
Scaffolds-Scaffold Market
Umi-React Application Framework
dumi-Component doc generator
qiankun-Micro-Frontends Framework
ahooks-React Hooks Library
Ant Motion-Motion Solution
China Mirror 🇨🇳

Community

Awesome Ant Design
Medium
Twitter
yuqueAnt Design in YuQue
Ant Design in Zhihu
Experience Cloud Blog
seeconfSEE Conf-Experience Tech Conference

Help

GitHub
Change Log
FAQ
Bug Report
Issues
Discussions
StackOverflow
SegmentFault

Ant XTechMore Products

yuqueYuQue-Document Collaboration Platform
AntVAntV-Data Visualization
EggEgg-Enterprise Node.js Framework
kitchenKitchen-Sketch Toolkit
xtechAnt Financial Experience Tech
Theme Editor
Made with ❤ by
Ant Group and Ant Design Community

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

Basic Usage.

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select, Space } from 'antd';

const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};

const App: React.FC = () => (
  <Space wrap>
    <Select
      defaultValue="lucy"
      style={{ width: 120 }}
      onChange={handleChange}
      options={[
        { value: 'jack', label: 'Jack' },
        { value: 'lucy', label: 'Lucy' },
        { value: 'Yiminghe', label: 'yiminghe' },
        { value: 'disabled', label: 'Disabled', disabled: true },
      ]}
    />
    <Select
      defaultValue="lucy"
      style={{ width: 120 }}
      disabled
      options={[{ value: 'lucy', label: 'Lucy' }]}
    />
    <Select
      defaultValue="lucy"
      style={{ width: 120 }}
      loading
      options={[{ value: 'lucy', label: 'Lucy' }]}
    />
    <Select
      defaultValue="lucy"
      style={{ width: 120 }}
      allowClear
      options={[{ value: 'lucy', label: 'Lucy' }]}
    />
  </Space>
);

export default App;
multiple selection

Multiple selection, selecting from existing items.

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select, Space } from 'antd';
import type { SelectProps } from 'antd';

const options: SelectProps['options'] = [];

for (let i = 10; i < 36; i++) {
  options.push({
    label: i.toString(36) + i,
    value: i.toString(36) + i,
  });
}

const handleChange = (value: string[]) => {
  console.log(`selected ${value}`);
};

const App: React.FC = () => (
  <Space style={{ width: '100%' }} direction="vertical">
    <Select
      mode="multiple"
      allowClear
      style={{ width: '100%' }}
      placeholder="Please select"
      defaultValue={['a10', 'c12']}
      onChange={handleChange}
      options={options}
    />
    <Select
      mode="multiple"
      disabled
      style={{ width: '100%' }}
      placeholder="Please select"
      defaultValue={['a10', 'c12']}
      onChange={handleChange}
      options={options}
    />
  </Space>
);

export default App;
Custom selection render

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

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select, Space } from 'antd';

const { Option } = Select;

const handleChange = (value: string[]) => {
  console.log(`selected ${value}`);
};

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

export default App;
Tags

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

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';

const options: SelectProps['options'] = [];

for (let i = 10; i < 36; i++) {
  options.push({
    value: i.toString(36) + i,
    label: i.toString(36) + i,
  });
}

const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};

const App: React.FC = () => (
  <Select
    mode="tags"
    style={{ width: '100%' }}
    placeholder="Tags Mode"
    onChange={handleChange}
    options={options}
  />
);

export default App;
coordinate

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
TypeScript
JavaScript
import React, { useState } from 'react';
import { Select, Space } from 'antd';

const provinceData = ['Zhejiang', 'Jiangsu'];

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

type CityName = keyof typeof cityData;

const App: React.FC = () => {
  const [cities, setCities] = useState(cityData[provinceData[0] as CityName]);
  const [secondCity, setSecondCity] = useState(cityData[provinceData[0] as CityName][0]);

  const handleProvinceChange = (value: CityName) => {
    setCities(cityData[value]);
    setSecondCity(cityData[value][0]);
  };

  const onSecondCityChange = (value: CityName) => {
    setSecondCity(value);
  };

  return (
    <Space wrap>
      <Select
        defaultValue={provinceData[0]}
        style={{ width: 120 }}
        onChange={handleProvinceChange}
        options={provinceData.map((province) => ({ label: province, value: province }))}
      />
      <Select
        style={{ width: 120 }}
        value={secondCity}
        onChange={onSecondCityChange}
        options={cities.map((city) => ({ label: city, value: city }))}
      />
    </Space>
  );
};

export default App;
Get value of selected item

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
TypeScript
JavaScript
import React from 'react';
import { Select } from 'antd';

const handleChange = (value: { value: string; label: React.ReactNode }) => {
  console.log(value); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
};

const App: React.FC = () => (
  <Select
    labelInValue
    defaultValue={{ value: 'lucy', label: 'Lucy (101)' }}
    style={{ width: 120 }}
    onChange={handleChange}
    options={[
      {
        value: 'jack',
        label: 'Jack (100)',
      },
      {
        value: 'lucy',
        label: 'Lucy (101)',
      },
    ]}
  />
);

export default App;
Search and Select Users

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

expand codeexpand code
TypeScript
JavaScript
import React, { useMemo, useRef, useState } from 'react';
import { Select, Spin } from 'antd';
import type { SelectProps } from 'antd/es/select';
import debounce from 'lodash/debounce';

export interface DebounceSelectProps<ValueType = any>
  extends Omit<SelectProps<ValueType | ValueType[]>, 'options' | 'children'> {
  fetchOptions: (search: string) => Promise<ValueType[]>;
  debounceTimeout?: number;
}

function DebounceSelect<
  ValueType extends { key?: string; label: React.ReactNode; value: string | number } = any,
>({ fetchOptions, debounceTimeout = 800, ...props }: DebounceSelectProps<ValueType>) {
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState<ValueType[]>([]);
  const fetchRef = useRef(0);

  const debounceFetcher = useMemo(() => {
    const loadOptions = (value: string) => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);

      fetchOptions(value).then((newOptions) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }

        setOptions(newOptions);
        setFetching(false);
      });
    };

    return debounce(loadOptions, debounceTimeout);
  }, [fetchOptions, debounceTimeout]);

  return (
    <Select
      labelInValue
      filterOption={false}
      onSearch={debounceFetcher}
      notFoundContent={fetching ? <Spin size="small" /> : null}
      {...props}
      options={options}
    />
  );
}

// Usage of DebounceSelect
interface UserValue {
  label: string;
  value: string;
}

async function fetchUserList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);

  return fetch('https://randomuser.me/api/?results=5')
    .then((response) => response.json())
    .then((body) =>
      body.results.map(
        (user: { name: { first: string; last: string }; login: { username: string } }) => ({
          label: `${user.name.first} ${user.name.last}`,
          value: user.login.username,
        }),
      ),
    );
}

const App: React.FC = () => {
  const [value, setValue] = useState<UserValue[]>([]);

  return (
    <DebounceSelect
      mode="multiple"
      value={value}
      placeholder="Select users"
      fetchOptions={fetchUserList}
      onChange={(newValue) => {
        setValue(newValue as UserValue[]);
      }}
      style={{ width: '100%' }}
    />
  );
};

export default App;
Hide Already Selected

Hide already selected options in the dropdown.

expand codeexpand code
TypeScript
JavaScript
import React, { useState } from 'react';
import { Select } from 'antd';

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

const App: React.FC = () => {
  const [selectedItems, setSelectedItems] = useState<string[]>([]);

  const filteredOptions = OPTIONS.filter((o) => !selectedItems.includes(o));

  return (
    <Select
      mode="multiple"
      placeholder="Inserted are removed"
      value={selectedItems}
      onChange={setSelectedItems}
      style={{ width: '100%' }}
      options={filteredOptions.map((item) => ({
        value: item,
        label: item,
      }))}
    />
  );
};

export default App;
Custom Tag Render

Allows for custom rendering of tags.

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select, Tag } from 'antd';
import type { CustomTagProps } from 'rc-select/lib/BaseSelect';

const options = [{ value: 'gold' }, { value: 'lime' }, { value: 'green' }, { value: 'cyan' }];

const tagRender = (props: CustomTagProps) => {
  const { label, value, closable, onClose } = props;
  const onPreventMouseDown = (event: React.MouseEvent<HTMLSpanElement>) => {
    event.preventDefault();
    event.stopPropagation();
  };
  return (
    <Tag
      color={value}
      onMouseDown={onPreventMouseDown}
      closable={closable}
      onClose={onClose}
      style={{ marginRight: 3 }}
    >
      {label}
    </Tag>
  );
};

const App: React.FC = () => (
  <Select
    mode="multiple"
    showArrow
    tagRender={tagRender}
    defaultValue={['gold', 'cyan']}
    style={{ width: '100%' }}
    options={options}
  />
);

export default App;
Big Data

Select use virtual scroll which get better performance than 3.0.

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import type { SelectProps } from 'antd';
import { Divider, Select, Typography } from 'antd';

const { Title } = Typography;

const options: SelectProps['options'] = [];

for (let i = 0; i < 100000; i++) {
  const value = `${i.toString(36)}${i}`;
  options.push({
    label: value,
    value,
    disabled: i === 10,
  });
}

const handleChange = (value: string[]) => {
  console.log(`selected ${value}`);
};

const App: React.FC = () => (
  <>
    <Title level={3}>Ant Design 4.0</Title>
    <Title level={4}>{options.length} Items</Title>
    <Select
      mode="multiple"
      style={{ width: '100%' }}
      placeholder="Please select"
      defaultValue={['a10', 'c12']}
      onChange={handleChange}
      options={options}
    />

    <Divider />

    <Title level={3}>Ant Design 3.0</Title>
    <iframe
      title="Ant Design 3.0 Select demo"
      src="https://codesandbox.io/embed/solitary-voice-m3vme?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      style={{ width: '100%', height: 300 }}
    />
  </>
);

export default App;
Placement

You can manually specify the position of the popup via placement.

expand codeexpand code
TypeScript
JavaScript
import React, { useState } from 'react';
import type { RadioChangeEvent } from 'antd';
import { Radio, Select } from 'antd';
import type { SelectCommonPlacement } from 'antd/es/_util/motion';

const App: React.FC = () => {
  const [placement, SetPlacement] = useState<SelectCommonPlacement>('topLeft');

  const placementChange = (e: RadioChangeEvent) => {
    SetPlacement(e.target.value);
  };

  return (
    <>
      <Radio.Group value={placement} onChange={placementChange}>
        <Radio.Button value="topLeft">topLeft</Radio.Button>
        <Radio.Button value="topRight">topRight</Radio.Button>
        <Radio.Button value="bottomLeft">bottomLeft</Radio.Button>
        <Radio.Button value="bottomRight">bottomRight</Radio.Button>
      </Radio.Group>
      <br />
      <br />
      <Select
        defaultValue="HangZhou"
        style={{ width: 120 }}
        dropdownMatchSelectWidth={false}
        placement={placement}
        options={[
          {
            value: 'HangZhou',
            label: 'HangZhou #310000',
          },
          {
            value: 'NingBo',
            label: 'NingBo #315000',
          },
          {
            value: 'WenZhou',
            label: 'WenZhou #325000',
          },
        ]}
      />
    </>
  );
};

export default App;
Select with search field

Search the options while expanded.

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select } from 'antd';

const onChange = (value: string) => {
  console.log(`selected ${value}`);
};

const onSearch = (value: string) => {
  console.log('search:', value);
};

const App: React.FC = () => (
  <Select
    showSearch
    placeholder="Select a person"
    optionFilterProp="children"
    onChange={onChange}
    onSearch={onSearch}
    filterOption={(input, option) =>
      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
    }
    options={[
      {
        value: 'jack',
        label: 'Jack',
      },
      {
        value: 'lucy',
        label: 'Lucy',
      },
      {
        value: 'tom',
        label: 'Tom',
      },
    ]}
  />
);

export default App;
Sizes

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
TypeScript
JavaScript
import React, { useState } from 'react';
import { Radio, Select, Space } from 'antd';
import type { SizeType } from 'antd/es/config-provider/SizeContext';
import type { SelectProps, RadioChangeEvent } from 'antd';

const options: SelectProps['options'] = [];

for (let i = 10; i < 36; i++) {
  options.push({
    value: i.toString(36) + i,
    label: i.toString(36) + i,
  });
}

const handleChange = (value: string | string[]) => {
  console.log(`Selected: ${value}`);
};

const App: React.FC = () => {
  const [size, setSize] = useState<SizeType>('middle');

  const handleSizeChange = (e: RadioChangeEvent) => {
    setSize(e.target.value);
  };

  return (
    <>
      <Radio.Group value={size} onChange={handleSizeChange}>
        <Radio.Button value="large">Large</Radio.Button>
        <Radio.Button value="middle">Default</Radio.Button>
        <Radio.Button value="small">Small</Radio.Button>
      </Radio.Group>
      <br />
      <br />
      <Space direction="vertical" style={{ width: '100%' }}>
        <Select
          size={size}
          defaultValue="a1"
          onChange={handleChange}
          style={{ width: 200 }}
          options={options}
        />
        <Select
          mode="multiple"
          size={size}
          placeholder="Please select"
          defaultValue={['a10', 'c12']}
          onChange={handleChange}
          style={{ width: '100%' }}
          options={options}
        />
        <Select
          mode="tags"
          size={size}
          placeholder="Please select"
          defaultValue={['a10', 'c12']}
          onChange={handleChange}
          style={{ width: '100%' }}
          options={options}
        />
      </Space>
    </>
  );
};

export default App;
Search with sort

Search the options with sorting.

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select } from 'antd';

const App: React.FC = () => (
  <Select
    showSearch
    style={{ width: 200 }}
    placeholder="Search to Select"
    optionFilterProp="children"
    filterOption={(input, option) => (option?.label ?? '').includes(input)}
    filterSort={(optionA, optionB) =>
      (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
    }
    options={[
      {
        value: '1',
        label: 'Not Identified',
      },
      {
        value: '2',
        label: 'Closed',
      },
      {
        value: '3',
        label: 'Communicated',
      },
      {
        value: '4',
        label: 'Identified',
      },
      {
        value: '5',
        label: 'Resolved',
      },
      {
        value: '6',
        label: 'Cancelled',
      },
    ]}
  />
);

export default App;
Option Group

Using OptGroup to group the options.

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select } from 'antd';

const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};

const App: React.FC = () => (
  <Select
    defaultValue="lucy"
    style={{ width: 200 }}
    onChange={handleChange}
    options={[
      {
        label: 'Manager',
        options: [
          { label: 'Jack', value: 'jack' },
          { label: 'Lucy', value: 'lucy' },
        ],
      },
      {
        label: 'Engineer',
        options: [{ label: 'yiminghe', value: 'Yiminghe' }],
      },
    ]}
  />
);

export default App;
Search Box

Search with remote data.

expand codeexpand code
TypeScript
JavaScript
import React, { useState } from 'react';
import { Select } from 'antd';
import jsonp from 'fetch-jsonp';
import qs from 'qs';
import type { SelectProps } from 'antd';

let timeout: ReturnType<typeof setTimeout> | null;
let currentValue: string;

const fetch = (value: string, callback: Function) => {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;

  const fake = () => {
    const str = qs.stringify({
      code: 'utf-8',
      q: value,
    });
    jsonp(`https://suggest.taobao.com/sug?${str}`)
      .then((response: any) => response.json())
      .then((d: any) => {
        if (currentValue === value) {
          const { result } = d;
          const data = result.map((item: any) => ({
            value: item[0],
            text: item[0],
          }));
          callback(data);
        }
      });
  };

  timeout = setTimeout(fake, 300);
};

const SearchInput: React.FC<{ placeholder: string; style: React.CSSProperties }> = (props) => {
  const [data, setData] = useState<SelectProps['options']>([]);
  const [value, setValue] = useState<string>();

  const handleSearch = (newValue: string) => {
    if (newValue) {
      fetch(newValue, setData);
    } else {
      setData([]);
    }
  };

  const handleChange = (newValue: string) => {
    setValue(newValue);
  };

  return (
    <Select
      showSearch
      value={value}
      placeholder={props.placeholder}
      style={props.style}
      defaultActiveFirstOption={false}
      showArrow={false}
      filterOption={false}
      onSearch={handleSearch}
      onChange={handleChange}
      notFoundContent={null}
      options={(data || []).map((d) => ({
        value: d.value,
        label: d.text,
      }))}
    />
  );
};

const App: React.FC = () => <SearchInput placeholder="input search text" style={{ width: 200 }} />;

export default App;
Automatic tokenization

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

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';

const options: SelectProps['options'] = [];

for (let i = 10; i < 36; i++) {
  options.push({
    value: i.toString(36) + i,
    label: i.toString(36) + i,
  });
}

const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};

const App: React.FC = () => (
  <Select
    mode="tags"
    style={{ width: '100%' }}
    onChange={handleChange}
    tokenSeparators={[',']}
    options={options}
  />
);

export default App;
Custom dropdown

Customize the dropdown menu via dropdownRender. If you want to close the dropdown after clicking the custom content, you need to control open prop, here is an codesandbox.

expand codeexpand code
TypeScript
JavaScript
import React, { useState, useRef } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Divider, Input, Select, Space, Button } from 'antd';
import type { InputRef } from 'antd';

let index = 0;

const App: React.FC = () => {
  const [items, setItems] = useState(['jack', 'lucy']);
  const [name, setName] = useState('');
  const inputRef = useRef<InputRef>(null);

  const onNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const addItem = (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
    e.preventDefault();
    setItems([...items, name || `New item ${index++}`]);
    setName('');
    setTimeout(() => {
      inputRef.current?.focus();
    }, 0);
  };

  return (
    <Select
      style={{ width: 300 }}
      placeholder="custom dropdown render"
      dropdownRender={(menu) => (
        <>
          {menu}
          <Divider style={{ margin: '8px 0' }} />
          <Space style={{ padding: '0 8px 4px' }}>
            <Input
              placeholder="Please enter item"
              ref={inputRef}
              value={name}
              onChange={onNameChange}
            />
            <Button type="text" icon={<PlusOutlined />} onClick={addItem}>
              Add item
            </Button>
          </Space>
        </>
      )}
      options={items.map((item) => ({ label: item, value: item }))}
    />
  );
};

export default App;
Bordered-less

Bordered-less style component.

expand codeexpand code
TypeScript
JavaScript
import { Select, Space } from 'antd';
import React from 'react';

const App: React.FC = () => (
  <Space wrap>
    <Select
      defaultValue="lucy"
      style={{ width: 120 }}
      bordered={false}
      options={[
        { value: 'jack', label: 'Jack' },
        { value: 'lucy', label: 'Lucy' },
        { value: 'Yiminghe', label: 'yiminghe' },
      ]}
    />
    <Select
      defaultValue="lucy"
      style={{ width: 120 }}
      disabled
      bordered={false}
      options={[{ value: 'lucy', label: 'Lucy' }]}
    />
  </Space>
);

export default App;
Responsive maxTagCount

Auto collapse to tag with responsive case. Not recommend use in large form case since responsive calculation has a perf cost.

expand codeexpand code
TypeScript
JavaScript
import React, { useState } from 'react';
import type { SelectProps } from 'antd';
import { Select, Space } from 'antd';

interface ItemProps {
  label: string;
  value: string;
}

const options: ItemProps[] = [];

for (let i = 10; i < 36; i++) {
  const value = i.toString(36) + i;
  options.push({
    label: `Long Label: ${value}`,
    value,
  });
}

const App: React.FC = () => {
  const [value, setValue] = useState(['a10', 'c12', 'h17', 'j19', 'k20']);

  const selectProps: SelectProps = {
    mode: 'multiple',
    style: { width: '100%' },
    value,
    options,
    onChange: (newValue: string[]) => {
      setValue(newValue);
    },
    placeholder: 'Select Item...',
    maxTagCount: 'responsive',
  };

  return (
    <Space direction="vertical" style={{ width: '100%' }}>
      <Select {...selectProps} />
      <Select {...selectProps} disabled />
    </Space>
  );
};

export default App;
Status

Add status to Select with status, which could be error or warning.

expand codeexpand code
TypeScript
JavaScript
import React from 'react';
import { Select, Space } from 'antd';

const App: React.FC = () => (
  <Space direction="vertical" style={{ width: '100%' }}>
    <Select status="error" style={{ width: '100%' }} />
    <Select status="warning" style={{ width: '100%' }} />
  </Space>
);

export default App;

API

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

Select props

PropertyDescriptionTypeDefaultVersion
allowClearShow clear buttonbooleanfalse
autoClearSearchValueWhether the current search will be cleared on selecting an item. Only applies when mode is set to multiple or tagsbooleantrue
autoFocusGet focus by defaultbooleanfalse
borderedWhether has border stylebooleantrue
clearIconThe custom clear iconReactNode-
defaultActiveFirstOptionWhether active first option by defaultbooleantrue
defaultOpenInitial open state of dropdownboolean-
defaultValueInitial selected optionstring | string[] |
number | number[] |
LabeledValue | LabeledValue[]
-
disabledWhether disabled selectbooleanfalse
popupClassNameThe className of dropdown menustring-4.23.0
dropdownMatchSelectWidthDetermine whether the dropdown 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 | numbertrue
dropdownRenderCustomize dropdown content(originNode: ReactNode) => ReactNode-
dropdownStyleThe style of dropdown menuCSSProperties-
fieldNamesCustomize node label, value, options field nameobject{ label: label, value: value, options: options }4.17.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) => number-4.9.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
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-
optionFilterPropWhich prop value of option will be used for filter if filterOption is true. If options is set, it should be set to labelstringvalue
optionLabelPropWhich prop value of option will render as content of select. Examplestringchildren
optionsSelect options. Will get better perf than jsx definition{ label, value }[]-
placeholderPlaceholder of selectReactNode-
placementThe position where the selection box pops upbottomLeft bottomRight topLeft topRightbottomLeft
removeIconThe custom remove iconReactNode-
searchValueThe current input "search" textstring-
showArrowWhether to show the drop-down arrowbooleantrue(for single select), false(for multiple select)
showSearchWhether select is searchablebooleansingle: false, multiple: true
sizeSize of Select inputlarge | middle | smallmiddle
statusSet validation status'error' | 'warning'-4.19.0
suffixIconThe custom suffix iconReactNode-
tagRenderCustomize tag render, only applies when mode is set to multiple or tags(props) => ReactNode-
tokenSeparatorsSeparator used to tokenize, only applies when mode="tags"string[]-
valueCurrent selected option (considered as a immutable array)string | string[] |
number | number[] |
LabeledValue | LabeledValue[]
-
virtualDisable virtual scroll when set to falsebooleantrue4.1.0
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 openfunction(open)-
onFocusCalled when focusfunction-
onInputKeyDownCalled when key pressedfunction-
onMouseEnterCalled when mouse enterfunction-
onMouseLeaveCalled when mouse leavefunction-
onPopupScrollCalled when dropdown scrollsfunction-
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 .

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 labelstring | React.Element-

FAQ

Why sometime search will show 2 same option when in tags mode?

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 dropdownRender, the select dropdown will not be closed?

You can control it by open prop: codesandbox.

I don't want dropdown close when click inside dropdownRender?

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

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

Why sometime customize Option cause scroll break?

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:

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

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

Why a11y test report missing aria- props?

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.

Lucy
Lucy
Lucy
Lucy
a10
c12
 
a10
c12
 
China
 
 
Tags Mode
Zhejiang
Hangzhou
Lucy (101)
 
Select users
 
Inserted are removed
gold
cyan
 

Ant Design 4.0

100000 Items

a10
c12
 

Ant Design 3.0



HangZhou #310000
Select a person


a1
a10
c12
 
a10
c12
 
Search to Select
Lucy
input search text
 
custom dropdown render
Lucy
Lucy
+ 4 ...
 
+ 4 ...