user10454516
user10454516

Reputation: 1143

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?

Upvotes: 3

Views: 8799

Answers (2)

Lumen27
Lumen27

Reputation: 81

For anyone who's stumbled onto this old question:

The codesandbox example in the accepted answer is a good start, but when you select the option from the list, the select becomes empty/blank.

A few things have to be done to fix this:

  1. This is happens because the OPACITY is set to 0 on the input after selecting an option. I just set my css to target the input and gave it opacity: 1 !important.
  2. Now when you select a value, it won't disappear, but you'll only see your inputValue(that you typed). To fix this and show the value you selected, you just have to add a setState change inside of onChange for the inputValue.

I added some extra measures on my end to make sure it works, like using ref and selecting the input and modifying it's value, but thats probably not needed.

Upvotes: 0

Laura
Laura

Reputation: 8630

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.

Upvotes: 6

Related Questions