Randall
Randall

Reputation: 2858

React-select onChange trigger when user select same option

The onChange of a react-select drop down is getting triggered when I select an already selected value in the drop down. Is there a way to configure react-select to not trigger onChange event if already selected value is selected again.

  handleOnChange(value) {
    console.log("test");
    this.setState({ multiValue: value });
  }
  render() {
    return (
      <div>
        <Select.Creatable
          options={this.state.options}
          onChange={this.handleOnChange.bind(this)}
          value={this.state.multiValue}
          showNewOptionAtTop={false}
        />
      </div>
    );
  }

As you can see the console log calling even if the value is the same. Codesandbox

Upvotes: 0

Views: 2650

Answers (2)

Alireza Zarei
Alireza Zarei

Reputation: 314

I'm not sure whether you can disable the change event but as a workaround You can simply hold the current value of the selected item and return from the change handler if the selected item was the previous one like @ahmetkilinc answer, also menu items have an option

isDisabled

that you can change to true when one item is selected, therefore it can't be selected anymore.

Upvotes: 0

ahmetkilinc
ahmetkilinc

Reputation: 684

You can control the value on onChange of react select.

I changed your onChange function with arrow function:

onChange={value => {
    if (value !== this.state.multiValue){
       this.handleOnChange(value);
    }
}}

codesandbox

Upvotes: 3

Related Questions