Search code examples
reactjsdropdownhtml-selectreact-select

react-select: Automatically suggest "other" option when you have no options for the search


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.


Solution

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

    • Disable the default option filter so it doesn't mess with your custom filter.
    • Control the options state.
    • Filter out the options as the user type and update the options state.

    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)}
        />
      );
    }
    

    Live Demo

    Edit 66978600/automatically-suggest-other-option-when-have-no-options-for-the-search-in-reac