Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain input value on option selected in react-select

Tags:

react-select

I'm using react-select 2 in my project. Every time a user selects an option, the input value is cleared which causes the option list to change.
Is there any way to retain the input value so the user can select multiple options? here is what i tried:

<Select
    closeMenuOnSelect={false}
    blurInputOnSelect={false}
    isMulti
    loadOptions={this.resultProvider.bind(this)}
    inputValue={this.state.searchKey}
    onInputChange={this.handleInputChanged.bind(this)}
  />


handleInputChanged(input, reason) {
    if (reason.action === "set-value") {
        return;
    }
    this.setState({
        ...this.state,
        searchKey: input
    });
}

I have created a demo to demonstrate this issue: https://codesandbox.io/s/345rp0m041

Note that this issue only happend with Async select.

Thanks for advices!

like image 992
Sỹ Lê Avatar asked Sep 09 '18 10:09

Sỹ Lê


1 Answers

I think you are pretty close. A quick way (might not be the best way though) to solving this issue would be to add two more checks to the handleInputChanged method:

handleInputChanged(input, reason) {
    if (reason.action === "set-value" ||
        reason.action === "input-blur" ||
        reason.action === "menu-close") {
          return;
    }
    this.setState({
      ...this.state,
      searchKey: input
    });
  }

Here's a working demo of your code: https://codesandbox.io/s/8n9mx057k0

Hope this helps!

Side note: in V1 of react-select we had the onSelectResetsInput prop to retain the value of the input box when the user selects an option. But seems like it's no longer available

like image 57
Sahan Serasinghe Avatar answered Oct 09 '22 07:10

Sahan Serasinghe