Reputation: 77
I want to search for an option in ANTD Select element. I am using 'showSearch' option to auto-suggestion for the Select element. But, the value I want to provide is not available as option for the element. Can we manually enter the value, which is not present as options, in that Select element and continue with the search.
We are able to enter values when 'mode=tags' is set, but we can select multiple options in that case. Is it possible to achieve the same, but restrict to only single option at a time, not multiple?
Upvotes: 2
Views: 2686
Reputation: 833
I also found it annoying that this feature is available in tags
mode but not in multiple
. I don't know if this is the best solution anyone could come up with, but I solved it for myself by wrapping the Select
component with my own component like this:
import { useState, useRef, useCallback } from 'react';
import { Select } from 'antd';
function FlexibleSelect(props) {
const { options: baseOptions, ...selectProps } = props;
const [options, setOptions] = useState([...baseOptions]);
const currentValue = useRef();
const onSearch = useCallback((value) => {
currentValue.current = value;
if (value && !baseOptions.some((op) => op.indexOf(value) === 0)) {
setOptions([...baseOptions, value]);
} else {
setOptions([...baseOptions]);
}
}, [baseOptions]);
return (
<Select
{...selectProps}
showSearch
onSearch={onSearch}
options={options.map((option) => ({
label: option,
value: option
}))}
/>
);
Upvotes: 3
Reputation: 2544
To achieve, this you should try the antd AutoComplete
component as it affords this kind of flexibility. It allows you to enter values that don't exist on the options list and you can only select a value at a time. You'll need to pass in AutoComplete.Option
as children of the component (not the usual Select.Option
)
Here's some documentation: https://ant.design/components/auto-complete/
Upvotes: 2