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

import { Select } from '@fibrous/semi-ui-solid';

Write the options as <Select.Option> and <Select.OptGroup>.

Basic Usage

Each Option tag must declare the value attribute. label is the text of the option, used for search and in callbacks; children is what the option shows and can be a JSX element, and without children the label shows





Code
import { Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    return (
        <>
            <Select aria-label="业务线" defaultValue="douyin" style={{ width: '120px' }}>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying" disabled>
                    剪映
                </Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="业务线" defaultValue="douyin" disabled style={{ width: '120px' }}>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="业务线" placeholder="请选择业务线" style={{ width: '120px' }}>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying" disabled>
                    剪映
                </Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
        </>
    );
}

Pass Option as an array

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

Code
import { Select } from '@fibrous/semi-ui-solid';

const list = [
    { value: 'douyin', label: '抖音', otherKey: 0 },
    { value: 'ulikecam', label: '轻颜相机', disabled: true, otherKey: 1 },
    { value: 'jianying', label: '剪映', otherKey: 2 },
    { value: 'toutiao', label: '今日头条', otherKey: 3 },
];

export default function SelectDemo() {
    return <Select aria-label="业务线" placeholder="请选择业务线" style={{ width: '180px' }} optionList={list} />;
}

Multi-choice

Since v2.28, the selector will have its own maxHeight 270, and the content can be viewed by scrolling vertically after it exceeds.

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

Configure ellipsisTrigger (>= v2.28.0) to do adaptive processing on the overflow part of the tag. When the width is insufficient, the last tag content will be truncated. After enabling this function, there will be a certain performance loss, and it is not recommended to use it in large form scenarios

Configure expandRestTagsOnClick (>= v2.28.0) to display all remaining tags by clicking when maxTagCount is set

Use showRestTagsPopover (>= v2.22.0) to set whether hover +N displays Popover after exceeding maxTagCount, the default is false. Also, popovers can be configured in the restTagsPopoverProps property

Configuration max Properties can limit the maximum number of options and cannot be selected beyond the maximum limit, while triggering the onExceed callback







Code
import { Select, Toast } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    return (
        <>
            <Select aria-label="Select 示例" multiple style={{ width: '320px' }} defaultValue={['douyin', 'ulikecam']}>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying">剪映</Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="Select 示例" multiple maxTagCount={2} showRestTagsPopover restTagsPopoverProps={{ position: 'top' }} style={{ width: '320px' }} defaultValue={['douyin', 'ulikecam', 'jianying']}>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying">剪映</Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>

            <br />
            <br />
            <Select aria-label="Select 示例" multiple style={{ width: '320px' }} defaultValue={['douyin']} max={2} onExceed={() => Toast.warning('最多只允许选择两项')}>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying">剪映</Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="Select 示例" multiple maxTagCount={2} showRestTagsPopover restTagsPopoverProps={{ position: 'top' }} style={{ width: '220px' }} defaultValue={['xigua', 'ulikecam', 'jianying', 'douyin']} ellipsisTrigger expandRestTagsOnClick>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying">剪映</Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
        </>
    );
}

With Group

Grouping Option with Select.OptGroup (only supports declaring the options as children, and does not support pass in through optionList). Use the label prop for the group title, which takes text only

Code
import { Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    return (
        <Select aria-label="地区" placeholder="" style={{ width: '180px' }} filter>
            <Select.OptGroup label="Asia">
                <Select.Option value="a-1" label="China" />
                <Select.Option value="a-2" label="Korea" />
            </Select.OptGroup>
            <Select.OptGroup label="Europe">
                <Select.Option value="b-1" label="Germany" />
                <Select.Option value="b-2" label="France" />
            </Select.OptGroup>
            <Select.OptGroup label="South America">
                <Select.Option value="c-1" label="Peru" />
            </Select.OptGroup>
        </Select>
    );
}
Code
import { For } from 'solid-js';
import { Select } from '@fibrous/semi-ui-solid';

const data = [
    {
        label: 'Asia',
        children: [
            { value: 'a-1', label: 'China' },
            { value: 'a-2', label: 'Korea' },
        ],
    },
    {
        label: 'Europe',
        children: [
            { value: 'b-1', label: 'Germany' },
            { value: 'b-2', label: 'France' },
        ],
    },
    {
        label: 'South America',
        children: [{ value: 'c-1', label: 'Peru' }],
    },
];

export default function SelectDemo() {
    return (
        <Select aria-label="地区" placeholder="" style={{ width: '180px' }} filter>
            <For each={data}>
                {(group) => (
                    <Select.OptGroup label={group.label}>
                        <For each={group.children}>{(option) => <Select.Option value={option.value} label={option.label} />}</For>
                    </Select.OptGroup>
                )}
            </For>
        </Select>
    );
}

Different sizes

Size: small / default / large





Code
import { Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    return (
        <>
            <Select aria-label="small" placeholder="请选择业务线" style={{ width: '180px' }} size="small">
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="default" placeholder="请选择业务线" style={{ width: '180px' }}>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="large" placeholder="请选择业务线" style={{ width: '180px' }} size="large">
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
            </Select>
        </>
    );
}

Different validate status

validateStatus: default / warning / error





Code
import { Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    return (
        <>
            <Select aria-label="default" style={{ width: '180px' }}>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="warning" style={{ width: '180px' }} validateStatus="warning">
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="error" style={{ width: '180px' }} validateStatus="error">
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
            </Select>
        </>
    );
}

Configure Prefix, Suffix, Clear Button

  • You can pass the selection box prefix through prefix, the selection box suffix through suffix, for text or a JSX element
    The left and right padding is automatically brought when the content passed in by prefix and suffix is text or Icon. If it is a custom element, 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


Code
import { IconGift, IconVigoLogo } from '@fibrous/semi-icons-solid';
import { Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    return (
        <>
            <Select aria-label="Select 示例" style={{ width: '320px' }} defaultValue="ulikecam" prefix={<IconVigoLogo />} showClear>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying">剪映</Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
            <br />
            <br />
            <Select aria-label="Select 示例" style={{ width: '320px' }} defaultValue="ulikecam" prefix={<IconVigoLogo />} suffix={<IconGift />} showArrow={false}>
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying">剪映</Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
        </>
    );
}

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

outerBottomSlot:

innerBottomSlot:

Code
import { Select } from '@fibrous/semi-ui-solid';

const innerSlotStyle = {
    'background-color': 'var(--color-white)',
    height: '36px',
    display: 'flex',
    'align-items': 'center',
    cursor: 'pointer',
    'padding-left': '32px',
    'border-top': '1px solid var(--semi-color-border)',
    'border-radius': '0 0 6px 6px',
    color: 'var(--semi-color-link)',
};
const outSlotStyle = {
    'background-color': 'var(--semi-color-fill-0)',
    height: '36px',
    display: 'flex',
    'padding-left': '32px',
    color: 'var(--semi-color-link)',
    'align-items': 'center',
    cursor: 'pointer',
    'border-top': '1px solid var(--semi-color-border)',
    'border-radius': '0 0 6px 6px',
};

export default function SelectDemo() {
    return (
        <div>
            <p>outerBottomSlot:</p>
            <Select
                aria-label="outerBottomSlot"
                style={{ width: '300px' }}
                dropdownStyle={{ width: '180px' }}
                maxHeight={150}
                outerBottomSlot={
                    <div style={outSlotStyle}>
                        <span style={{ color: 'var(--semi-color-link)' }}>未找到应用?</span>
                    </div>
                }
                placeholder="自定义外侧底部slot,始终显示"
                defaultOpen
                autoAdjustOverflow={false}
                position="bottom"
            >
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying">剪映</Select.Option>
                <Select.Option value="duoshan">多闪</Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
            <p style={{ 'margin-top': '200px' }}>innerBottomSlot:</p>
            <Select aria-label="innerBottomSlot" style={{ width: '300px' }} dropdownStyle={{ width: '180px' }} maxHeight={150} innerBottomSlot={<div style={innerSlotStyle}>点击加载更多</div>} placeholder="自定义内侧底部slot,滚动至底部显示">
                <Select.Option value="douyin">抖音</Select.Option>
                <Select.Option value="ulikecam">轻颜相机</Select.Option>
                <Select.Option value="jianying">剪映</Select.Option>
                <Select.Option value="duoshan">多闪</Select.Option>
                <Select.Option value="xigua">西瓜视频</Select.Option>
            </Select>
        </div>
    );
}

Using outerTopSlot to insert content

Code
import { createSignal } from 'solid-js';
import { RadioGroup, Select } from '@fibrous/semi-ui-solid';

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

const list: Record<string, Item[]> = {
    component: [
        { value: 'select', label: '选择器' },
        { value: 'tabs', label: '标签' },
        { value: 'avatar', label: '头像' },
        { value: 'button', label: '按钮' },
    ],
    design: [
        { value: 'color', label: '颜色' },
        { value: 'dark', label: '暗色模式' },
        { value: 'icon', label: '图标' },
        { value: 'font', label: '字体' },
    ],
    feedback: [
        { value: 'faq', label: '常见问题' },
        { value: 'join', label: '加入用户群' },
        { value: 'hornbill', label: '犀鸟反馈问题' },
    ],
};

const categoryOptions = [
    { value: 'component', label: '组件' },
    { value: 'design', label: '设计' },
    { value: 'feedback', label: '反馈' },
];

export default function SelectDemo() {
    const [key, setKey] = createSignal('component');
    const [value, setValue] = createSignal<Item | undefined>({ value: 'faq', label: '常见问题' });

    // The radio group switches with arrow keys, so categories need no tabpanel association
    return (
        <Select
            aria-label="选项"
            defaultOpen
            autoAdjustOverflow={false}
            value={value()}
            onChangeWithObject
            onChange={(obj) => setValue(obj)}
            style={{ width: '200px' }}
            outerTopSlot={
                <div style={{ padding: '8px 12px', 'border-bottom': '0.5px solid var(--semi-color-border)' }}>
                    <RadioGroup type="button" buttonSize="small" aria-label="选项分类" options={categoryOptions} value={key()} onChange={(e) => setKey(String(e.target.value))} />
                </div>
            }
            optionList={list[key()]}
        />
    );
}

Controlled component

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

Code
import { createSignal } from 'solid-js';
import { Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    const [value, setValue] = createSignal<string | undefined>('xigua');
    return (
        <Select aria-label="业务线" value={value()} style={{ width: '300px' }} onChange={(v) => setValue(v)} placeholder="受控的Select">
            <Select.Option value="douyin">抖音</Select.Option>
            <Select.Option value="ulikecam">轻颜相机</Select.Option>
            <Select.Option value="jianying">剪映</Select.Option>
            <Select.Option value="xigua">西瓜视频</Select.Option>
        </Select>
    );
}

Dynamic Modification Options

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



Code
import { For, createSignal } from 'solid-js';
import { Button, Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    const [options, setOptions] = createSignal([1, 2, 3, 4]);
    const add = () => {
        const length = Math.ceil(Math.random() * 10);
        setOptions(Array.from({ length }, (_, i) => i + 1));
    };
    return (
        <>
            <Select aria-label="数字" style={{ width: '180px' }} placeholder="请选择" value={4}>
                <For each={options()}>{(option) => <Select.Option value={option}>{option}</Select.Option>}</For>
            </Select>
            <br />
            <br />
            <Button onClick={add}>changeOptions Dynamic</Button>
        </>
    );
}

Linkage Select

Use a controlled value to link different Selects. If it is a complex linkage with a hierarchical relationship, it is recommended to use Cascader components directly

Code
import { For, createSignal } from 'solid-js';
import { Select } from '@fibrous/semi-ui-solid';

const provinces = ['四川', '广东'];
const maps: Record<string, string[]> = {
    四川: ['成都', '都江堰'],
    广东: ['广州', '深圳', '东莞'],
};

export default function SelectDemo() {
    const [province, setProvince] = createSignal(provinces[0]);
    const citys = () => maps[province()];
    const [city, setCity] = createSignal<string | undefined>(citys()[0]);

    const provinceChange = (newProvince?: string) => {
        if (!newProvince) {
            return;
        }
        setProvince(newProvince);
        setCity(maps[newProvince][0]);
    };

    return (
        <>
            <Select aria-label="省份" style={{ width: '150px', margin: '10px' }} onChange={provinceChange} value={province()}>
                <For each={provinces}>{(pro) => <Select.Option value={pro}>{pro}</Select.Option>}</For>
            </Select>
            <Select aria-label="城市" style={{ width: '150px', margin: '10px' }} value={city()} onChange={(v) => setCity(v)}>
                <For each={citys()}>{(c) => <Select.Option value={c}>{c}</Select.Option>}</For>
            </Select>
        </>
    );
}

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)

Search position

The default search input is displayed on the Select Trigger. You can specify different positions through searchPosition, and you can choose dropdown or trigger. Available after v2.61.0
If you want to customize the placeholder of the Input search box in the dropdown, you can control it through searchPlaceholder
If the searchPosition is trigger, when showClear=true, clicking the clear button of the input will clear the selected items and the search text in the input at the same time
If the searchPosition is dropdown, when showClear=true, clicking the clear button of the trigger will clear the selected items, clicking the clear button in the dropdown input will clear search text



Code
import { Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    return (
        <>
            <Select aria-label="单选" filter searchPosition="dropdown" style={{ width: '200px' }} defaultValue="ulikecam" placeholder="我的搜索框在下拉菜单中" searchPlaceholder="带搜索功能的单选">
                <Select.Option value="douyin" label="抖音" />
                <Select.Option value="ulikecam" label="轻颜相机" />
                <Select.Option value="jianying" label="剪映" />
                <Select.Option value="xigua" label="西瓜视频" />
            </Select>
            <br />
            <br />
            <Select aria-label="多选" filter searchPosition="dropdown" multiple style={{ width: '300px' }} defaultValue={['semi-1']} placeholder="我的搜索框在下拉菜单中" searchPlaceholder="带搜索功能的多选" autoClearSearchValue={false}>
                <Select.Option value="semi-0" label="Semi-0" />
                <Select.Option value="semi-1" label="Semi-1" />
                <Select.Option value="semi-2" label="Semi-2" />
                <Select.Option value="semi-3" label="Semi-3" />
                <Select.Option value="semi-4" label="Semi-4" />
            </Select>
        </>
    );
}

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 a controlled value, and get the keyword from onSearch

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.

Code
import { Select, type SelectOptionProps } from '@fibrous/semi-ui-solid';

function searchLabel(sugInput: string, option: SelectOptionProps) {
    return String(option.label).toUpperCase().includes(sugInput.toUpperCase());
}

export default function SelectDemo() {
    return (
        <Select aria-label="业务线" filter={searchLabel} style={{ width: '180px' }} placeholder="try douyin">
            <Select.Option value="douyin" label="douyin" />
            <Select.Option value="ulikecam" label="HOTSOON" />
            <Select.Option value="jianying" label="PIPIXIA" />
            <Select.Option value="xigua" label="XIGUA" />
        </Select>
    );
}

Custom selection rendering

By default, the children of the selected Option, or its label without children, is backfilled into the selection box.
But you can customize the rendering of the selection box through the renderSelectedItem function

  • Select: renderSelectedItem(optionNode: object) => content: JSX.Element
  • Multiple Select: renderSelectedItem(optionNode: object, { index: number, disabled: boolean, onClose: function }) => { isRenderInTag: boolean, content: JSX.Element }
    • 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
  • Other props written on Select.Option (such as email in the demo) are passed in with optionNode
Code
import { For } from 'solid-js';
import { Avatar, Select, Tag, type SelectRenderMultipleSelectedItemFn, type SelectRenderSingleSelectedItemFn } from '@fibrous/semi-ui-solid';

interface ListItem {
    name: string;
    email: string;
    avatar: string;
}

const list: ListItem[] = [
    {
        name: '夏可漫',
        email: 'xiakeman@example.com',
        avatar: '/assets/placeholder/avatar-a.svg',
    },
    {
        name: '申悦',
        email: 'shenyue@example.com',
        avatar: '/assets/root-web-sites/bag.jpeg',
    },
    {
        name: '曲晨一',
        email: 'quchenyi@example.com',
        avatar: '/assets/placeholder/avatar-c.svg',
    },
    {
        name: '文嘉茂',
        email: 'wenjiamao@example.com',
        avatar: '/assets/root-web-sites/6fbafc2d-e3e6-4cff-a1e2-17709c680624.png',
    },
];

const optionStyle = {
    display: 'flex',
    'padding-left': '24px',
    'padding-top': '10px',
    'padding-bottom': '10px',
};

const renderSelectedItem: SelectRenderSingleSelectedItemFn = (optionNode) => (
    <div style={{ display: 'flex', 'align-items': 'center' }}>
        <Avatar src={String(optionNode.avatar)} alt="" size="small" />
        <span style={{ 'margin-left': '8px' }}>{String(optionNode.email)}</span>
    </div>
);

const renderMultipleWithTag =
    (avatarShape: 'circle' | 'square'): SelectRenderMultipleSelectedItemFn =>
    (optionNode, { onClose }) => ({
        isRenderInTag: false,
        content: (
            <Tag avatarSrc={String(optionNode.avatar)} avatarShape={avatarShape} closable onClose={onClose} size="large">
                {String(optionNode.name)}
            </Tag>
        ),
    });

const renderCustomOption = (item: ListItem) => (
    <Select.Option {...item} value={item.name} style={optionStyle} showTick>
        <Avatar size="small" src={item.avatar} alt="" />
        <div style={{ 'margin-left': '8px' }}>
            <div style={{ 'font-size': '14px' }}>{item.name}</div>
            <div style={{ color: 'var(--color-text-2)', 'font-size': '12px', 'line-height': '16px', 'font-weight': 'normal' }}>{item.email}</div>
        </div>
    </Select.Option>
);

export default function SelectDemo() {
    return (
        <>
            <Select placeholder="请选择" style={{ width: '280px', height: '40px' }} onChange={(v) => console.log(v)} defaultValue="申悦" renderSelectedItem={renderSelectedItem}>
                <For each={list}>{renderCustomOption}</For>
            </Select>
            <Select placeholder="请选择" maxTagCount={2} style={{ width: '280px', 'margin-top': '20px' }} onChange={(v) => console.log(v)} defaultValue={['申悦', '曲晨一']} multiple renderSelectedItem={renderMultipleWithTag('circle')}>
                <For each={list}>{renderCustomOption}</For>
            </Select>
            <Select placeholder="请选择" maxTagCount={2} style={{ width: '280px', 'margin-top': '20px' }} onChange={(v) => console.log(v)} defaultValue={['申悦', '曲晨一']} multiple renderSelectedItem={renderMultipleWithTag('square')}>
                <For each={list}>{renderCustomOption}</For>
            </Select>
        </>
    );
}

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

Code
import { Select } from '@fibrous/semi-ui-solid';

export default function SelectDemo() {
    return (
        <Select aria-label="业务线" placeholder="自定义弹出层样式的" style={{ width: '180px' }} dropdownStyle={{ width: '250px' }} dropdownClassName="test">
            <Select.Option value="douyin">抖音</Select.Option>
            <Select.Option value="ulikecam">轻颜相机</Select.Option>
            <Select.Option value="jianying">剪映</Select.Option>
            <Select.Option value="xigua">西瓜视频</Select.Option>
        </Select>
    );
}

Get all attribute of selected option

By default, through onChange you 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 })

onChange回调:

onChange回调:

Code
import { createSignal } from 'solid-js';
import { Select, TextArea } from '@fibrous/semi-ui-solid';

interface Item {
    value: string;
    label: string;
    type: number;
}

const list: Item[] = [
    { value: 'douyin', label: '抖音', type: 1 },
    { value: 'ulikecam', label: '轻颜相机', type: 2 },
    { value: 'jianying', label: '剪映', type: 3 },
    { value: 'toutiao', label: '今日头条', type: 4 },
];

export default function SelectDemo() {
    const [cbValue, setCbValue] = createSignal<Item>();
    const [multipleCbValue, setMultipleCbValue] = createSignal<Item[]>();

    const onChange = (value?: Item) => {
        setCbValue(value);
        console.log(value);
    };

    const onMultipleChange = (value: Item[]) => {
        setMultipleCbValue(value);
        console.log(value);
    };

    return (
        <div>
            <div>
                <Select aria-label="单选" style={{ width: '150px' }} onChangeWithObject optionList={list} placeholder="单选" defaultValue={list[0]} onChange={onChange} />
                <h4 id="select-on-change-with-object-single">onChange回调:</h4>
                <TextArea aria-labelledby="select-on-change-with-object-single" style={{ width: '320px', 'margin-bottom': '48px' }} autosize value={JSON.stringify(cbValue())} rows={2} />
            </div>
            <div>
                <Select aria-label="多选" style={{ width: '320px' }} onChangeWithObject multiple optionList={list} onChange={onMultipleChange} placeholder="多选" />
                <h4 id="select-on-change-with-object-multiple">onChange回调:</h4>
                <TextArea aria-labelledby="select-on-change-with-object-multiple" style={{ width: '320px' }} autosize value={JSON.stringify(multipleCbValue())} />
            </div>
        </div>
    );
}

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 a JSX element, note that you need to customize the style). Without it the locale text for "Create" followed by the input is shown. Its arguments are (inputValue, isFocus, style), and with virtualization you must apply style to the custom element

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



With renderCreateItem
Code
import { Select } from '@fibrous/semi-ui-solid';

const optionList = [
    { value: 'douyin', label: '抖音' },
    { value: 'ulikecam', label: '轻颜相机' },
    { value: 'jianying', label: '剪映' },
    { value: 'toutiao', label: '今日头条' },
];

export default function SelectDemo() {
    return (
        <>
            <Select aria-label="业务线" style={{ width: '400px' }} optionList={optionList} allowCreate multiple filter onChange={(v) => console.log(v)} defaultActiveFirstOption />
            <br />
            <br />
            <Select
                aria-label="业务线"
                style={{ width: '400px' }}
                optionList={optionList}
                allowCreate
                multiple
                filter
                placeholder="With renderCreateItem"
                renderCreateItem={(input, _isFocus, style) => <div style={{ padding: '10px', ...style }}>Create Item:{input}</div>}
                onChange={(v) => console.log(v)}
                defaultActiveFirstOption
            />
        </>
    );
}

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 270 (before v2.20.8 was 300)
  • width: Option list width value, default 100%
  • itemSize: The height of each line of Option, must be passed
Code
import { Select } from '@fibrous/semi-ui-solid';

const newOptions = Array.from({ length: 3000 }, (_, i) => ({ label: `option-${i}`, value: i }));
const virtualize = {
    height: 270,
    width: '100%',
    itemSize: 36, // px
};

export default function SelectDemo() {
    return <Select aria-label="virtualize" placeholder="拥有3k个Option的Select" style={{ width: '260px' }} filter virtualize={virtualize} optionList={newOptions} />;
}

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

If you want to keep the search and filter ability without rendering the Input structure yourself, you can also set searchPosition='dropdown' to put the default search box in the dropdown list

The parameters of triggerRender are as follows

interface TriggerRenderProps {
    value: SelectedItemProps[]; // All currently selected options
    inputValue: string; // The current search keyword
    onSearch: (inputValue: string) => void; // Updates the search keyword. Call it when the value of your custom Input changes, to synchronize the state to the Select internal. filter needs to be set too
    onRemove: (option: OptionProps) => void; // Removes a single selected option, which needs at least label and value
    onClear: (e?: MouseEvent) => void; // Clears the selection. When bound to a control inside the trigger, pass the click event so that click does not reopen the dropdown
    disabled: boolean; // Whether to disable Select
    placeholder: JSX.Element; // Select placeholder
    componentProps: Record<string, unknown>; // All props passed to Select by users
}

不同背景色的触发器



使用 circle Tag 作为触发器

Code
import { createSignal } from 'solid-js';
import { IconAppCenter, IconChevronDown } from '@fibrous/semi-icons-solid';
import { Select, Tag, type SelectTriggerRenderProps } from '@fibrous/semi-ui-solid';

const list = [
    { value: 'douyin', label: '抖音' },
    { value: 'ulikecam', label: '轻颜相机' },
    { value: 'jianying', label: '剪映' },
    { value: 'toutiao', label: '今日头条' },
];

const triggerRender = (props: SelectTriggerRenderProps) => (
    <div
        style={{
            'min-width': '112px',
            'background-color': 'var(--semi-color-primary-light-default)',
            height: '32px',
            display: 'flex',
            'align-items': 'center',
            'padding-left': '12px',
            'border-radius': '3px',
            color: 'var(--semi-color-primary)',
        }}
    >
        <div style={{ 'font-weight': 600, 'flex-shrink': 0, 'font-size': '14px' }}>业务线</div>
        <div
            style={{
                margin: '4px',
                'white-space': 'nowrap',
                'text-overflow': 'ellipsis',
                'flex-grow': 1,
                overflow: 'hidden',
            }}
        >
            {props.value.map((item) => item.label).join(' , ')}
        </div>
        <IconAppCenter style={{ 'margin-right': '8px', 'flex-shrink': 0 }} />
    </div>
);

const triggerRender2 = (props: SelectTriggerRenderProps) => (
    <div
        style={{
            margin: '4px',
            'white-space': 'nowrap',
            'text-overflow': 'ellipsis',
            'flex-grow': 1,
            overflow: 'hidden',
            display: 'flex',
            'align-items': 'center',
        }}
    >
        <Tag size="large" color="cyan" shape="circle" suffixIcon={<IconChevronDown />}>
            {props.value.map((item) => item.label).join(' / ')}
        </Tag>
    </div>
);

export default function SelectDemo() {
    const [valList, setValList] = createSignal(['douyin', 'ulikecam']);
    return (
        <div>
            <h4>不同背景色的触发器</h4>
            <Select aria-label="不同背景色的触发器" value={valList()} triggerRender={triggerRender} optionList={list} onChange={(value) => setValList(value)} multiple filter searchPosition="dropdown" style={{ width: '240px' }} />
            <br />
            <br />
            <h4>使用 circle Tag 作为触发器</h4>
            <Select aria-label="circle Tag 触发器" value={valList()} onChange={(value) => setValList(value)} triggerRender={triggerRender2} optionList={list} filter multiple searchPosition="dropdown" style={{ width: '240px', 'margin-top': '20px', outline: 0 }} />
        </div>
    );
}

The following is a more complex example: Reusing the drag-and-sort capability of TagInput and adding sorting to Select through a custom trigger.

可对已选项拖拽重新排序的 Select

Code
import { createSignal } from 'solid-js';
import { Select, TagInput, type SelectTriggerRenderProps } from '@fibrous/semi-ui-solid';

const list = [
    { value: 'douyin', label: '抖音' },
    { value: 'ulikecam', label: '轻颜相机' },
    { value: 'jianying', label: '剪映' },
    { value: 'toutiao', label: '今日头条' },
];

export default function SelectDemo() {
    const [valList, setValList] = createSignal(['douyin', 'ulikecam']);
    const [inputVal, setInputVal] = createSignal('');

    const handleSort = (currentLabels: string[]) => {
        setValList(currentLabels.flatMap((item) => list.find((i) => i.label === item)?.value ?? []));
    };

    const triggerRender = (props: SelectTriggerRenderProps) => (
        <div role="presentation" onKeyDown={(e) => e.stopPropagation()}>
            <TagInput
                draggable
                allowDuplicates={false}
                value={props.value.map((item) => String(item.label))}
                inputValue={inputVal()}
                onInputChange={(word) => {
                    props.onSearch(word);
                    setInputVal(word);
                }}
                onChange={handleSort}
                showClear
            />
        </div>
    );

    return (
        <>
            <h4>可对已选项拖拽重新排序的 Select </h4>
            <Select aria-label="可拖拽排序的 Select" value={valList()} triggerRender={triggerRender} optionList={list} onChange={(value) => setValList(value)} multiple filter style={{ width: '240px' }} />
        </>
    );
}

Custom Option Render

  • Simple customization: Pass a JSX element as the children of Option to control the rendering of the candidates, and the content will automatically bring styles such as padding, background color, etc.; pass a text label as well for search
  • 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
    The parameter is { id, value, label, selected, focused, disabled, inputValue, class, style, onClick, onMouseEnter } plus any other props written on the Option. Its fields update with the state, so do not destructure it; read props.xxx in the JSX. Notice:
    1. The style in the parameter needs to be consumed on wrapper dom, otherwise it will not be able to be used normally in virtualization scenarios
    2. The class and onMouseEnter in the parameter need to be bound on the wrapper dom, otherwise the display will be problematic when the upper and lower keyboards are operated
    3. The styles of selected, focused, disabled, etc. state need to be added by yourself, and you can get the relative boolean value from the parameter
    4. Bind the onClick in the parameter to the wrapper dom so that a click selects the option
    5. Put the id in the parameter on the wrapper dom with role="option", aria-selected and aria-disabled: the Select points aria-activedescendant at that id, so screen readers announce the option reached with the arrow keys; Select also uses this id to scroll the option into view when the dropdown opens or the arrow keys move


多选
Code
import { createSignal } from 'solid-js';
import clsx from 'clsx';
import { Checkbox, Highlight, Select, type SelectOptionRenderProps } from '@fibrous/semi-ui-solid';

const optionList = [
    { value: 'douyin', label: '抖音', otherKey: 0 },
    { value: 'ulikecam', label: '轻颜相机', disabled: true, otherKey: 1 },
    { value: 'jianying', label: '剪映', otherKey: 2 },
    { value: 'toutiao', label: '今日头条', otherKey: 3 },
];

export default function SelectDemo() {
    const [inputValue, setInputValue] = createSignal('');

    // Put style on the outer DOM or the virtual list breaks; add selected/focused/disabled styles from props;
    // bind onMouseEnter and class on the outer DOM or arrow keys display wrongly; put id there so screen
    // readers announce the option the arrow keys reach
    const renderOptionItem = (props: SelectOptionRenderProps) => (
        <div
            id={props.id}
            role="option"
            aria-selected={props.selected}
            aria-disabled={props.disabled}
            style={props.style}
            class={clsx(props.class, 'custom-option-render', {
                'custom-option-render-focused': props.focused,
                'custom-option-render-disabled': props.disabled,
                'custom-option-render-selected': props.selected,
            })}
            onClick={(e) => props.onClick(e)}
            onMouseEnter={(e) => props.onMouseEnter(e)}
        >
            <Checkbox checked={props.selected} />
            <div class="option-right">
                <Highlight sourceString={String(props.label)} searchWords={[inputValue()]} />
            </div>
        </div>
    );

    return (
        <>
            <Select aria-label="单选" filter placeholder="单选" onSearch={(v) => setInputValue(v)} dropdownClassName="components-select-demo-renderOptionItem" optionList={optionList} style={{ width: '180px' }} renderOptionItem={renderOptionItem} />
            <br />
            <br />
            <Select aria-label="多选" filter placeholder="多选" multiple onSearch={(v) => setInputValue(v)} dropdownClassName="components-select-demo-renderOptionItem" optionList={optionList} style={{ width: '320px' }} renderOptionItem={renderOptionItem} />
        </>
    );
}
.components-select-demo-renderOptionItem {
    .custom-option-render {
        display: flex;
        font-size: 14px;
        line-height: 20px;
        word-break: break-all;
        padding-left: 12px;
        padding-right: 12px;
        padding-top: 8px;
        padding-bottom: 8px;
        color: var(--semi-color-text-0);
        position: relative;
        display: flex;
        align-items: center;
        cursor: pointer;
        box-sizing: border-box;
        .option-right {
            margin-left: 8px;
            display: inline-flex;
            align-items: center;
        }
        &:active {
            background-color: var(--semi-color-fill-1);
        }
        &-focused {
            background-color: var(--semi-color-fill-0);
        }
        &-selected {
            //font-weight: 700;
        }
        &-disabled {
            color: var(--semi-color-disabled-text);
            cursor: not-allowed;
        }
        &:first-of-type {
            margin-top: 4px;
        }
        &:last-of-type {
            margin-bottom: 4px;
        }
    }
}

API reference

Select Props

Props

PropertyDescriptionTypeDefault
allowCreateWhether items that are not in the dropdown can be created, used together with filter. onCreate fires on creation, and renderCreateItem customizes how the item renders.booleanfalse
aria-labelAccessible name of the combobox: the search input while it is in the trigger, otherwise the trigger. aria-labelledby takes precedence over it, and it takes precedence over insetLabel.string-
arrowIconCustom dropdown arrow icon on the right; null shows no icon. With showClear on and a value selected, hovering shows the clear icon first.JSX.Element-
autoAdjustOverflowWhether the popup flips its direction automatically when it is covered.booleantrue
autoClearSearchValueIn multiple mode with search on, whether the search keyword is cleared after an option is selected.booleantrue
autofocusWhether the Select is focused on mount.boolean-
borderlessWhether to use the borderless style.booleanfalse
childrenThe options. Direct children must be Select.Option or Select.OptGroup. A non-empty optionList takes precedence over children, and groups can only be declared with Select.OptGroup.JSX.Element-
clearIconCustom icon of the clear button, effective when showClear is true.JSX.Element-
clickToHideWhether clicking the Select collapses the dropdown while it is open.boolean-
defaultActiveFirstOptionWith no value selected, whether opening the dropdown highlights the first enabled option (Enter selects it). With a value selected, the first selected option is always highlighted.booleantrue
defaultOpenWhether the dropdown is open initially.booleanfalse
defaultValueThe initially selected value, read on mount only; an array in multiple mode. With onChangeWithObject it is the option object, which must contain value and label.TypeSelectValue<T>-
disabledWhether the Select is disabled. Falls back to the InputGroup it is in.boolean-
dropdownClassNameClass name of the dropdown popup.string-
dropdownMatchSelectWidthWhether the minimum width of the dropdown popup equals the Select.booleantrue
dropdownStyleStyle of the dropdown popup, for example to set width. The style on the root is not passed to the popup.JSX.CSSProperties | string-
ellipsisTriggerIn multiple mode with maxTagCount set, whether the content of the last tag is truncated when the width is not enough. It has some performance cost and is not recommended in large forms.booleanfalse
emptyContentContent shown when there are no options; null shows no empty state in the dropdown.JSX.Element-
expandRestTagsOnClickIn multiple mode with maxTagCount set, whether all tags are shown while the dropdown is open.booleanfalse
filterWhether the Select is searchable. true turns search on with the default strategy, which matches options whose label (or group title) contains the input; a function receives the input value and the option and returns true for a match.Typeboolean | ((inputValue: string, option: OptionProps) => boolean)false
idThe id of the trigger, from which the option ids derive. Generated when not set.string-
innerBottomSlotContent rendered at the bottom of the dropdown, inside the option list; it appears when the list is scrolled to the bottom.JSX.Element-
innerTopSlotContent rendered at the top of the dropdown, inside the option list; it appears when the list is scrolled to the top.JSX.Element-
inputPropsExtra props of the search Input when search is on; inputRef receives its native input element. The type leaves out value, onFocus and onChange, which Select handles itself.SelectInputProps-
insetLabelInset label inside the Select, also the name source of the combobox and the dropdown. It is neither rendered nor used as the name when prefix is set.JSX.Element-
insetLabelIdThe id of the insetLabel element, which the aria-labelledby of the combobox points to. Generated when not set.string-
loadingWhether the dropdown shows a loading animation.boolean-
maxThe maximum number of selected options, in multiple mode only; beyond it nothing more can be selected and onExceed fires.number-
maxHeightThe maximum height of the dropdown list; a number is in pixels and a string is used as is. When the height of virtualize exceeds the default, set this to the same value to avoid two scrollbars.string | number270
maxTagCountIn multiple mode, the maximum number of tags shown; the rest appear as +N.number-
motionWhether the popup uses animation.booleantrue
multipleWhether multiple options can be selected. It decides the type of the onChange argument: an array in multiple mode, a single value or undefined otherwise.Multiplefalse
onBlurCalled as focus leaves the Select; when a click outside closes the dropdown, the argument is the native mousedown event of that click.Type(e: FocusEvent | MouseEvent) => void-
onChangeCalled when the selected value changes; the argument is T or undefined in single mode and T[] in multiple mode.Type(value: SelectChangeValue<T, Multiple>) => void-
onChangeWithObjectWhether the option object is the value: when true, the onChange argument, value and defaultValue use the option object { value, label, ...rest }, which must contain value and label.booleanfalse
onClearCalled when the clear button is clicked.Type() => void-
onCreateCalled when an item is created with allowCreate on.Type(option: OptionProps) => void-
onDeselectCalled when an option is deselected, in multiple mode only; value is always the original value of the option.Type(value: OptionProps['value'], option: OptionProps) => void-
onDropdownVisibleChangeCalled when the dropdown opens or closes.Type(visible: boolean) => void-
onExceedCalled when selecting would exceed max, in multiple mode only.Type(option: OptionProps) => void-
onFocusCalled as focus enters the Select from outside.Type(e: FocusEvent) => void-
onListScrollCalled when the option list scrolls, including the scrolling of the virtual list.Type(e: Event) => void-
onSearchCalled when the search keyword changes. The second argument is the event that changed it: the native MouseEvent when the search is cleared after a click outside closes the dropdown, the passed event when called through the search method of the ref, and none when onSearch is called from triggerRender.Type(value: string, event?: InputChangeEvent | KeyboardEvent | MouseEvent) => void-
onSelectCalled when an option is selected; value is always the original value of the option, also with onChangeWithObject.Type(value: OptionProps['value'], option: OptionProps) => void-
optionListOptions as an array. Each item needs value and label; other fields travel with the option. A non-empty array takes precedence over children; groups are not supported.OptionProps[]-
outerBottomSlotContent rendered at the bottom of the dropdown, beside the option list; it is always shown.JSX.Element-
outerTopSlotContent rendered at the top of the dropdown, beside the option list; it is always shown.JSX.Element-
placeholderPlaceholder shown when nothing is selected.JSX.Element""
positionWhere the popup opens; the options are those of the position of Tooltip.Position-
prefixPrefix of the Select. Text or an icon gets side spacing automatically; a custom element has none.JSX.Element-
preventScrollWhether focusing keeps the browser from scrolling to the element, applied to the focus calls inside the component.boolean-
refReceives the trigger element, which carries the methods under Methods below; its focus() focuses the combobox (the search input while it is in the trigger) without opening the dropdown.TypeRef<SelectElement>-
remoteWhether search is remote. When on, typing does not filter locally; update optionList from onSearch instead.booleanfalse
renderCreateItemCustomizes how the create item renders with allowCreate on; its arguments are the input value, whether it is focused and the row style. With virtualize, the style must be applied to the custom element. When not set, the create text of the locale pack is shown before the input.Type(inputValue: OptionProps['value'], focus: boolean, style?: JSX.CSSProperties) => JSX.Element-
renderOptionItemFully customizes how the options in the dropdown render. Its argument holds id, label, value, selected, focused, disabled, inputValue, class, style, onClick and onMouseEnter. Put id on the outermost element together with role and aria-selected, and use class, style and onMouseEnter there too.Type(props: OptionRenderProps) => JSX.Element-
renderSelectedItemCustomizes how the selected items render in the Select. In single mode it returns the content; in multiple mode the second argument holds index, disabled and onClose, and it returns { isRenderInTag, content }, wrapping the content in a Tag when isRenderInTag is true.TypeByMultiple<Multiple, RenderSingleSelectedItemFn, RenderMultipleSelectedItemFn>-
restTagsPopoverPropsProps of the Popover that shows the remaining tags, such as position and trigger.PopoverProps-
searchPlaceholderPlaceholder of the search input when it is in the dropdown (searchPosition is dropdown).string-
searchPositionWhere the search input sits when search is on: trigger puts it in the Select, dropdown at the top of the dropdown. With trigger, the clear button of the Select also clears the search text; with dropdown it clears the selection only.'trigger' | 'dropdown'"trigger"
showArrowWhether to show the dropdown arrow on the right.booleantrue
showClearWhether to show the clear button. With a selected value or search text and not disabled, the button appears in the Select.booleanfalse
showRestTagsPopoverPast maxTagCount, whether hovering +N shows the remaining tags in a Popover.booleanfalse
sizeSize: small, default or large. The size of the InputGroup it is in takes precedence.SelectSize-
spacingDistance between the popup and the Select, in pixels.number | { x: number; y: number }-
stopPropagationWhether click events on the popup are stopped from bubbling.booleantrue
suffixSuffix of the Select. Text or an icon gets side spacing automatically; a custom element has none.JSX.Element-
triggerRenderCustomizes how the trigger renders. Its argument holds value, inputValue, onSearch, onClear, onRemove, disabled, placeholder and componentProps.Type(props: TriggerRenderProps) => JSX.Element-
validateStatusValidation status: default, warning or error. It only affects styles such as the background color.ValidateStatus-
valueThe selected value, an array in multiple mode. Passing it makes the Select controlled, used with onChange. With onChangeWithObject it is the option object, which must contain value and label.TypeSelectValue<T>-
virtualizeTurns on list virtualization to optimize performance with many options. itemSize is the height of each row and is required; height defaults to 270 and width to 100%.VirtualizeProps-

Methods

MethodDescriptionType
clearInputClears the value of the search input.Type() => void
closeCloses the dropdown.Type() => void
deselectAllClears all selected options.Type() => void
openOpens the dropdown.Type() => void
rePositionRecomputes the dropdown position from the trigger's current position at once. The dropdown already follows scrolling, window resizing, trigger moves and size changes of the trigger or list, so this is rarely needed; following a trigger move lands a frame late, so call this to align within the same frame.Type() => void
searchSearches as if the value were typed; it is set into the search input. Without an event, the second argument of onSearch is undefined.Type(value: string, event?: InputChangeEvent | KeyboardEvent | MouseEvent) => void
selectAllSelects every visible, enabled option, in multiple mode only.Type() => void

class, style, data-* and native attributes and listeners land on the root element, and style does not reach the dropdown popup (use dropdownStyle); with triggerRender the root no longer carries the style classes of Select itself. aria-label, aria-labelledby, aria-describedby, aria-errormessage, aria-invalid and aria-required land on the combobox; once the search input is mounted it is the combobox, and these attributes move to it. ref receives the root element, see Methods below.

Option Props

An option is identified by its value, which should not repeat within one Select; labels may repeat

Props

PropertyDescriptionTypeDefault
childrenContent of the option in the dropdown and in the selection; when set it shows instead of label and can be any JSX. It is not searched and is not the label in callbacks; pass label as well for search.JSX.Element-
classClass name of the option row.string-
disabledWhether the option is disabled.boolean-
labelText of the option, used for search, highlighting and callbacks, and shown when there are no children. value is used when it is not set.string | number-
showTickWhether a tick icon shows when the option is selected; shown by default.boolean-
styleStyle of the option row.JSX.CSSProperties | string-
valueThe value of the option, which identifies it; every option should declare one.string | number-

Select.Option is only read inside Select and renders nothing itself; its props become the option record. class, style and data-* land on the option row; other undeclared attributes never reach the DOM and travel with the option record to onSelect, onDeselect, renderSelectedItem and renderOptionItem, and to onChange once onChangeWithObject is on.

OptGroup Props

Props

PropertyDescriptionTypeDefault
childrenThe options in the group, which must be Select.Option.JSX.Element-
classClass name of the group title.string-
idThe id of the group title, which the aria-labelledby of the group points to. Generated when not set.string-
labelText of the group title, which takes part in the default search. When empty no title renders and the options are not wrapped in role="group".string | number-
styleStyle of the group title.JSX.CSSProperties | string-

Select.OptGroup is only read inside Select and renders nothing itself. class, style, id and other undeclared attributes land on the group title element.

Methods

The ref of Select receives the root element (the trigger), which carries the methods, typed as SelectElement (that is, HTMLDivElement & SelectHandle). Besides the methods below, the focus() of the element focuses the combobox (the search input while it is in the trigger) without opening the dropdown list.

MethodInstructions
open()Manually open dropdown list
close()Manually close dropdown list
clearInput()Manually clear value of the search input
selectAll()Select every shown, enabled option; multiple mode only
deselectAll()Manually clear selected options
search(value: string, event?: Event)Searches as if the value were typed into the search input, and the value is set to the input; without an event, the second parameter of onSearch is undefined
rePosition()Recomputes the dropdown position from the trigger's current position at once; the dropdown already follows scrolling, window resizing, trigger moves and size changes of the trigger or list, so this is rarely needed; following a trigger move lands a frame late, so call this to align within the same frame
import { Select, type SelectElement } from '@fibrous/semi-ui-solid';

function App() {
    let select: SelectElement | undefined;
    return (
        <>
            <Select ref={select} />
            <button onClick={() => select?.open()}>Open</button>
        </>
    );
}

Accessibility

ARIA

  • Following the ARIA 1.2 combobox pattern, exactly one element is the combobox at any time; the popup layer is a listbox and each option an option:
    • Without search, or with the search input in the dropdown (searchPosition="dropdown"), the Select trigger is a select-only combobox and the selected content is its value
    • With the search input in the trigger, the input itself is the combobox, with aria-autocomplete="list", and the trigger has no role and no Tab stop. In single mode the input appears only while searching, so the trigger is the combobox otherwise; the input is empty until the user types, so the selected text is linked to it as its description with aria-describedby. In multiple mode the input is always there
    • A search input in the dropdown stays a text box with aria-controls, aria-autocomplete and aria-activedescendant, named like the combobox
  • The combobox takes its name from, in order: aria-labelledby, aria-label, the rendered insetLabel (the combobox's aria-labelledby points at it, with an id the component generates when insetLabelId is not given; with a prefix the insetLabel is not rendered and does not name it), and otherwise "Select" from the locale. Pass a name that matches the form label. The listbox and a search input in the dropdown use the same name source, never the combobox itself. The selected content is the value of the combobox and is not part of the name
  • The combobox has aria-haspopup, aria-expanded, and aria-controls properties, indicating its relationship with the 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 options of an OptGroup with a label sit in a role="group" named by the group title (aria-labelledby), so screen readers announce the group of an option; a virtualized list shows no group titles and has no groups
  • While the dropdown is open, aria-activedescendant points at the option focused from the keyboard, which ensures that it is recognized when the narration is spoken; with a fully custom option rendering, put the id from the parameters on the option element (for more information, please refer to Managing Focus in Composites Using aria-activedescendant)

Keyboard and Focus

Select without Filter, or with the search box in the dropdown (searchPosition="dropdown"):

  • After Select is focused, keyboard users can open the dropdown menu with Space, Up Arrow, Down Arrow (including Alt + Down Arrow) or Enter. With a selected value the focus goes to the first selected option, so pressing Enter right away keeps the value; without one the current highlight stays, starting on the first enabled option (defaultActiveFirstOption defaults to true)
  • Home and End open the dropdown menu and move the focus to the first and the last enabled option
  • Typing a character opens the dropdown menu and moves the focus to the next option that starts with it; characters typed in quick succession match as a whole, and typing the same character again cycles through the options that start with it
  • 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, Home and End to move to either end, and a typed character to move to an option that starts with it
    • Enter or Space selects the focused option: a single Select selects it and collapses the panel, a multiple Select toggles it and stays open. While characters are being typed in quick succession, Space joins the search string instead of selecting. With the focus in the search box inside the dropdown, Home, End, Space and characters edit the search text without moving the option focus
  • In a multiple Select with the focus on a selected tag, keys act on the tag only: Backspace and Delete remove it, and Enter and Space neither open the dropdown menu nor change the value
  • 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: Up Arrow and Down Arrow switch options; Enter selects the focused option, collapsing the panel in a single Select and toggling it while staying open in a multiple Select; Esc or Tab closes the menu. Home, End, Space and characters belong to the input in the Select box and edit the search text without moving the option focus
  • 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

Clear button:

  • With showClear, a selected value or search text, and no disabled, the trigger renders a clear button. It is a native button named "Clear selection" from the locale, shown on hover, while the dropdown is open, or while focus is inside the Select
  • From the Select box, Tab moves to the clear button; Enter or Space clears, as a mouse click does, and the focus goes back 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

These are the component's internal Sass variables and cannot be overridden. To customize styles, override the --semi-* CSS variables (see the Design Token page) or write unlayered CSS rules.
Sass variableValueUsage
$transition_duration-select-bgvar(--semi-transition_duration-none)选择器-背景色-动画持续时间
$transition_function-select-bgvar(--semi-transition_function-easeIn)选择器-背景色-过渡曲线
$transition_delay-select-bgvar(--semi-transition_delay-none)选择器-背景色-延迟时间
$transition_duration-select-bordervar(--semi-transition_duration-none)选择器-边框-动画持续时间
$transition_function-select-bordervar(--semi-transition_function-easeIn)选择器-边框-过渡曲线
$transition_delay-select-bordervar(--semi-transition_delay-none)选择器-边框-延迟时间
$transition_duration-select_option-bgvar(--semi-transition_duration-none)选择器-选项-动画持续时间
$transition_function-select_option-bgvar(--semi-transition_function-easeIn)选择器-选项-过渡曲线
$transition_delay-select_option-bgvar(--semi-transition_delay-none)选择器-选项-延迟时间
$transform_scale-selectvar(--semi-transform_scale-none)选择框-变大
$transform_rotate-select-arrowvar(--semi-transform_rotate-none)选择框-箭头-旋转
$color-select-bg-defaultvar(--semi-color-fill-0)选择器输入框背景色 - 默认态
$color-select-bg-hovervar(--semi-color-fill-1)选择器输入框背景色 - 悬停态
$color-select-bg-activevar(--semi-color-fill-2)选择器输入框背景色 - 按下态
$color-select-bg-focusvar(--semi-color-fill-0)选择器输入框背景色 - 聚焦态
$color-select-border-defaulttransparent选择器输入框描边颜色
$color-select-border-hover$color-select-border-default选择器输入框描边颜色 - 悬浮
$color-select-border-activevar(--semi-color-focus-border)选择器输入框描边颜色 - 按下态
$color-select-border-focus$color-select-border-active选择器输入框描边颜色 - 选中态
$color-select_dropdown_input-border$color-select-border-default下拉搜索框底部描边颜色
$color-select_warning-bg-defaultvar(--semi-color-warning-light-default)警示选择器输入框背景色 - 默认态
$color-select_warning-border-defaultvar(--semi-color-warning-light-default)警示选择器输入框描边颜色 - 默认态
$color-select_warning-bg-hovervar(--semi-color-warning-light-hover)警示选择器输入框背景色 - 悬停态
$color-select_warning-border-hovervar(--semi-color-warning-light-hover)警示选择器输入框描边颜色 - 悬停态
$color-select_warning-bg-focusvar(--semi-color-warning-light-default)警示选择器输入框背景色 - 选中态
$color-select_warning-border-focusvar(--semi-color-warning)警示选择器输入框描边颜色 - 选中态
$color-select_warning-bg-activevar(--semi-color-warning-light-active)警示选择器输入框背景色 - 按下态
$color-select_warning-border-activevar(--semi-color-warning-light-active)警示选择器输入框描边颜色 - 按下态
$color-select_danger-bg-defaultvar(--semi-color-danger-light-default)报错选择器输入框背景色 - 默认态
$color-select_danger-border-defaultvar(--semi-color-danger-light-default)报错选择器输入框描边颜色 - 默认态
$color-select_danger-bg-hovervar(--semi-color-danger-light-hover)报错选择器输入框背景色 - 悬停态
$color-select_danger-border-hovervar(--semi-color-danger-light-hover)报错选择器输入框描边颜色 - 悬停态
$color-select_danger-bg-focusvar(--semi-color-danger-light-default)报错选择器输入框背景色 - 选中态
$color-select_danger-border-focusvar(--semi-color-danger)报错选择器输入框描边颜色 - 选中态
$color-select_danger-bg-activevar(--semi-color-danger-light-active)报错选择器输入框背景色 - 按下态
$color-select_danger-border-activevar(--semi-color-danger-light-active)报错选择器输入框描边颜色 - 按下态
$color-select_default-border-focusvar(--semi-color-focus-border)默认选择器输入框描边颜色 - 选中态
$color-select_main-text-defaultvar(--semi-color-text-0)选择器输入框回填内容文本颜色
$color-select-icon-defaultvar(--semi-color-text-2)选择器输入框图标颜色
$color-select_clearBtn-text-defaultvar(--semi-color-text-2)选择器输入框清空按钮颜色 - 默认态
$color-select_clearBtn-text-hovervar(--semi-color-primary)选择器输入框清空按钮颜色 - 悬停态
$color-select_input_disabled-bgvar(--semi-color-disabled-fill)禁用选择器输入框背景色
$color-select_input_disabled-border-focustransparent禁用选择器输入框描边颜色 - 聚焦态
$color-select_input_disabled-textvar(--semi-color-disabled-text)禁用选择器输入框回填内容文字颜色
$color-select_input_disabled-bg-hovervar(--semi-color-disabled-fill)禁用选择器输入框背景色 - 悬停态
$color-select_input_disabled-bg-focusvar(--semi-color-disabled-fill)禁用选择器输入框背景色 - 聚焦态
$color-select_input_placeholder-textvar(--semi-color-text-2)选择器输入框占位文本文字颜色
$color-select_option_main-textvar(--semi-color-text-0)选择器下拉菜单选项文本颜色
$color-select_option_keyword-textvar(--semi-color-primary)选择器下拉菜单选项匹配搜索结果文本颜色
$color-select_option-icon-defaulttransparent选择器下拉菜单选项图标颜色 - 默认态
$color-select_option-bg-hovervar(--semi-color-fill-0)选择器下拉菜单选项背景颜色 - 悬停态
$color-select_option-bg-activevar(--semi-color-fill-1)选择器下拉菜单选项背景颜色 - 按下态
$color-select_option_disabled-textvar(--semi-color-disabled-text)禁用选择器下拉菜单选项文字颜色
$color-select_option-icon-activevar(--semi-color-text-2)选择器下拉菜单选项图标颜色 - 选中态
$color-select_option-border-defaultvar(--semi-color-border)选择器下拉菜单分组标题分割线颜色
$color-select-option-bg-selectedtransparent选择器下拉菜单选项背景颜色 - 选中态
$color-select_create_tips-textvar(--semi-color-text-2)选择器下拉菜单新建选项提示文本颜色
$color-select_group-textvar(--semi-color-text-2)选择器下拉菜单分组标题文本颜色
$color-select_prefix_suffix_text-defaultvar(--semi-color-text-2)选择器输入框前后缀文本颜色
$height-select_large$height-control-large选择器输入框高度 - 大尺寸
$height-select_small$height-control-small选择器输入框高度 - 小尺寸
$height-select_default$height-control-default选择器输入框高度 - 默认尺寸
$width-select_option_tick$width-icon-small选择器下拉菜单项选中对勾图标大小
$width-select-border1px选择器输入框描边宽度
$width-select_arrow32px选择器输入框下拉箭头宽度
$width-select_arrow_empty12px选择器输入框下拉箭头为空时(有suffix icon)宽度
$width-select_clear-icon32px选择器输入框清空按钮宽度
$width-select_group_top-border$border-thickness-control选择器下拉菜单分组标题描边宽度
$height-select_multiple_input_small20px小尺寸多项选择器输入框Input框高度
$height-select_multiple_input_default24px默认多项选择器输入框Input框高度
$height-select_multiple_input_large24px大尺寸多项选择器输入框Input框高度
$width-select-border-hover$width-select-border选择器输入框描边宽度 - 悬浮
$width-select-border-focus$width-select-border-hover选择器输入框描边宽度 - 按下
$width-select-border-active$width-select-border-focus选择器输入框描边宽度 - 选中
$spacing-select_option_tick-marginRight$spacing-tight选择器下拉菜单选中对勾右侧外边距
$spacing-select_prefix_suffix_text-marginX$spacing-base-tight选择器输入框前后缀文本水平内边距
$spacing-select_prefix_suffix_text-marginY0px选择器输入框前后缀文本垂直内边距
$spacing-select_prefix_suffix_icon-marginX$spacing-tight选择器输入框前后缀图标水平内边距
$spacing-select_prefix_suffix_icon-marginY0px选择器输入框前后缀图标垂直内边距
$spacing-select_create_tips-marginRight$spacing-extra-tight创建新选项右侧外边距
$spacing-select_group-marginTop$spacing-extra-tight选择器下拉菜单分组标题顶部外边距
$spacing-select_group-paddingTop$spacing-base-tight选择器下拉菜单分组标题顶部内边距
$spacing-select_group-paddingBottom$spacing-extra-tight选择器下拉菜单分组标题底部内边距
$spacing-select_group-paddingLeft$spacing-base-tight + $width-select_option_tick + $spacing-select_option_tick-marginRight选择器下拉菜单分组标题左侧内边距
$spacing-select_group-paddingRight$spacing-base选择器下拉菜单分组标题右侧内边距
$spacing-select_loading_wrapper-paddingLeft$spacing-base选择器加载左侧内边距
$spacing-select_loading_wrapper-paddingRight$spacing-base选择器加载右侧内边距
$spacing-select_loading_wrapper-paddingTop$spacing-tight选择器加载顶部内边距
$spacing-select_loading_wrapper-paddingBottom$spacing-tight选择器加载底部内边距
$spacing-select_multiple_content_wrapper_empty-marginLeft$spacing-tight多项选择器空回填内容为空时左侧内边距
$spacing-select_multiple_selection-marginLeft$spacing-extra-tight多项选择器回填内容左侧内边距
$spacing-select_option-paddingLeft$spacing-base-tight选择器下拉菜单项左侧内边距
$spacing-select_option-paddingRight$spacing-base-tight选择器下拉菜单项右侧内边距
$spacing-select_option-paddingTop$spacing-tight选择器下拉菜单项顶部内边距
$spacing-select_option-paddingBottom$spacing-tight选择器下拉菜单项底部内边距
$spacing-select_tag-marginTop$spacing-super-tight - 1px多项选择器标签顶部外边距
$spacing-select_tag-marginRight$spacing-extra-tight多项选择器标签右侧外边距
$spacing-select_tag-marginBottom$spacing-super-tight - 1px多项选择器标签底部外边距
$spacing-select_selection-marginLeft$spacing-base-tight选择器内容区左侧外边距
$spacing-select_option_list-paddingTop$spacing-extra-tight选择器内容区顶部内边距
$spacing-select_option_list-paddingRight0px选择器内容区右侧内边距
$spacing-select_option_list-paddingBottom$spacing-extra-tight选择器内容区底部内边距
$spacing-select_option_list-paddingLeft0px选择器内容区左侧内边距
$spacing-select_dropdown_input_paddingTop8px下拉搜索框顶部内边距
$spacing-select_dropdown_input_paddingBottom8px下拉搜索框底部内边距
$spacing-select_dropdown_input_paddingRight12px下拉搜索框右侧内边距
$spacing-select_dropdown_input_paddingLeft12px下拉搜索框左侧内边距
$radius-selectvar(--semi-border-radius-small)选择器输入框圆角
$radius-select_option0px选择器待选项圆角
$font-select-fontWeight$font-weight-regular选择器文本字重
$font-select_keyword-fontWeight600选择器搜索结果命关键词中文本字重
$font-select_prefix_suffix-fontWeight$font-weight-bold选择器输入框前后缀文本字重
$opacity-select_selection_text_inactive0.4

TypeScript Generic Support

Select takes two generic parameters: T, the type of an option's value (the option object when onChangeWithObject is set), and Multiple, the type of the multiple prop. onChange receives T | undefined in single mode and T[] in multiple mode; when multiple is a boolean variable it receives T | T[] | undefined. onSelect and onDeselect receive the option's raw value (string | number), whatever T is. Both parameters are usually inferred from value and multiple; when you write T explicitly in multiple mode, write Multiple too.

import { Select } from '@fibrous/semi-ui-solid';

// T is inferred from value: string; value is string | undefined
<Select value={selectedValue()} onChange={(value) => setSelectedValue(value)}>
    <Select.Option value="option1">Option 1</Select.Option>
    <Select.Option value="option2">Option 2</Select.Option>
</Select>

// In multiple mode, value is string[]
<Select multiple value={selectedValues()} onChange={(value) => setSelectedValues(value)}>
    <Select.Option value="option1">Option 1</Select.Option>
    <Select.Option value="option2">Option 2</Select.Option>
</Select>

// Explicit generic parameters in multiple mode
<Select<string, true> multiple onChange={(value) => setSelectedValues(value)}>
    <Select.Option value="option1">Option 1</Select.Option>
    <Select.Option value="option2">Option 2</Select.Option>
</Select>

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 is turned on. If remote is not turned on, 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 turning on remote.

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

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