2
votes

There wasn't a good answer to this question so I'll answer it:

The problem is if you want to use the React-Select and you want persistent input value that doesn't get cleared on select or blur. This is not currently supported within the component, so a work-around is necessary.

I also answered this on one of the several issues raised on this topic https://github.com/JedWatson/react-select/issues/588
https://github.com/JedWatson/react-select/issues/3210

2

2 Answers

3
votes

you can also augment this with this to get desired effects

const App = () => {
  const [input, setInput] = useState("");
  const [inputSave, setSave] = useState("");
  
  return (
    <Select
      placeholder={inputSave} // when blurred & value == "" this shows
      value="" // always show placeholder
      inputValue={input} // allows you continue where you left off
      onInputChange={setInput} // allows for actually typing
      onMenuClose={() => setSave(input)} // before the input is cleared, save it
      onFocus={() => {
        setInput(inputSave);
        setSave(""); // prevents undesired placeholder value
      }} 
      blurInputOnSelect  // actually allows for ^^ to work
    />
  )
}

Edit sharp-pike-rnjbr

0
votes

The best way to go about this would be manually setting the input value (handling the onInputChange() event) only when the user is actually typing.

In other words, we need to disable ReactSelect's default behavior of clearing the input value on focus loss, menu close, and value select.

Example:

export default function App() {
  const [input, setInput] = useState("");

  const options = [
    { label: "first option", value: 1 },
    { label: "second option", value: 2 },
    { label: "third option", value: 3 }
  ];

  return (
    <Select
      options={options}
      inputValue={input}
      onInputChange={(value, action) => {
        // only set the input when the action that caused the
        // change equals to "input-change" and ignore the other
        // ones like: "set-value", "input-blur", and "menu-close"
        if (action.action === "input-change") setInput(value); // <---
      }}
    />
  );
}

Edit relaxed-beaver-e15x0