Search code examples
reactjsantd

Use Antd select with mode tags but allow only one selection


I'm using Antd Select for a project. My requirement is to use Select with mode='tags' as it allows user to create a new option, but I also want user to select only one option at a time (i.e either have a new option created or have an existing option selected shown in the select box). I tried using autoClearSearchValue but is of no use.

Appreciate the help.


Solution

  • Make the <Select /> to be controlled component. I write an example, the key logic is to control the selected value in onChange function;

    export default function MyTest() {
        const [data, setData] = React.useState<string[]>([]);
    
        return (
            <div>
                <Select
                    mode="tags"
                    onChange={(value, options) => {
                        // update data only when select one item or clear action
                        if (options?.length === 0 || options?.length === 1) {
                            setData(value);
                        }
                    }}
                    value={data}
                    options={[
                        {
                            label: "0",
                            value: "0",
                        },
                        {
                            label: "1",
                            value: "1",
                        },
                        {
                            label: "2",
                            value: "2",
                        },
                    ]}
                />
            </div>
        );
    }