I have a searchable dropdown field on my form, where the user does the research and selects normally.
What I need is if he types an option that does not exist, suggest the option "other" for him to select.
The "other" option already exists, I just don't know how to automatically suggest it.
I've seen about noOptionsMessage
, but it's not useful for me, I need you to suggest the option automatically.
Can you help me? Thanks.
There is a props called filterOption
to customize how you want your option filtered when the user types in the input, but it can only filter a single option and lacks the context of other options.
Because of that, to show the "other" option when no option available, you have to:
Below is an example to demonstrate what I meant:
import Select, { createFilter } from "react-select";
const filterOption = createFilter({});
const allOptions = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
const otherOption = { value: "other", label: "Other" };
export default function App() {
const [options, setOptions] = useState(allOptions);
const filterAllOptions = (rawInput: string) => {
const filteredOptions = allOptions.filter((o) => filterOption(o, rawInput));
if (filteredOptions.length === 0) {
filteredOptions.push(otherOption);
}
setOptions(filteredOptions);
};
return (
<Select
options={options}
filterOption={() => true} // disable the default option filter
onInputChange={(e) => filterAllOptions(e)}
/>
);
}