Search code examples
javascriptreactjsweb-component

How to make react-select disallow space in options?


We're looking into replacing an old tagging system with react-select 3.1. For historical reasons, we don't allow spaces in our tags (and changing that is complicated).

However! react-select seems to think spaces are totally fine in tags. What I think I want to do is make space be a thing that essentially says "hey I am done with this tag" just as enter and tab currently do — that matches our existing behavior and I would like to keep it if at all possible.

Is there a way to configure react-select to use this behavior?

Thanks!


Solution

  • You will need to manage the state of react-select, making it a controlled component, but this is how you can achieve this:

    import Select from "react-select/creatable";
    import { useState } from "react";
    
    export default function App() {
      const [value, setValue] = useState(null);
      const [inputValue, setInputValue] = useState("");
    
      return (
        <div className="App">
          <Select
            inputValue={inputValue}
            onInputChange={(v) => setInputValue(v)}
            onChange={(v) => setValue(v)}
            onKeyDown={(e) => {
              if (e.key === " ") {
                e.preventDefault();
                const newValue = {
                  label: inputValue,
                  value: inputValue
                };
                setValue((v) => {
                  return [...(v ?? []), newValue];
                });
                setInputValue("");
              }
            }}
            value={value}
            isMulti
            options={[
              {
                label: "aaa",
                value: "aaa"
              },
              {
                label: "bbb",
                value: "bbb"
              }
            ]}
          />
        </div>
      );
    }
    
    

    Edit exciting-meadow-679rh