Search code examples
reactjsreact-select

edit the last input of react-select


I am using react-select and just notice that when I already have value in the input field (either by user type or by choosing the option in menu list), then I blur the input then focus at it again - trying to edit my last input - its just start over from the beginning, not continue from the last character of the input. I just found this issue in the author's github. Its been raised from 2 years ago and still an open issue. Is there really no workaround to achieve this?


Solution

  • I recommend you to use controlled props inputValue and value pair with onChange and onInputChange like the following code:

    class App extends Component {
      constructor(props) {
        super(props);
    
        this.state = {
          inputValue: "",
          value: ""
        };
      }
      onInputChange = (option, { action }) => {
        console.log(option, action);
        if (action === "input-change") {
          const optionLength = option.length;
          const inputValue = this.state.inputValue;
          const inputValueLength = inputValue.length;
    
          const newInputValue =
            optionLength < inputValueLength
              ? option
              : this.state.inputValue + option[option.length - 1];
          this.setState({
            inputValue: newInputValue
          });
        }
      };
      onChange = option => {
        this.setState({
          value: option
        });
      };
      render() {
        return (
          <div className="App">
            <Select
              options={options}
              onChange={this.onChange}
              onInputChange={this.onInputChange}
              inputValue={this.state.inputValue}
              value={this.state.value}
            />
          </div>
        );
      }
    }
    

    In react-select v1 the props onSelectResetsInput set to false was doing this job but I guess for v2 you will need to do the trick.

    Here a live example.