Search code examples
typescriptonchangesetstatereact-select

How to set state of react-select component state when isMulti={true}?


Here is part of my code:

Table which I use:

const options = [
  { value: 'Orange', label: 'Orange' },
  { value: 'Banana', label: 'Banana' },
  { value: 'Apple', label: 'Apple' },
];

I create state "value" which is a table with initial state of empty table: value: [].

 private handleChange(value: any) {
    this.setState({ value: value });
  }

<Select
          value={this.props.selection}
          onChange={() => this.handleChange.bind(this)}
          options={options}
          isClearable={true}
          isMulti={true}
        />

{this.props.selection} is a type of the following class:

export class Selection {
  value: string;
  label: string;

  constructor(
    value: string,
    label: string,
  ) {
    this.value = value;
    this.label = label;
  }
}

When I select options from Select component the "value" state doesn't change. Do you have any idea what I'm doing wrong?


Solution

  • The callback you are assigning to onChange={() => this.handleChange.bind(this)} is actually not doing anything each time you change a value in your Select. The only thing that it does is to bind this to handleChange. It will not call the function.

    It's enough to pass the result of binding which is already a function.

    onChange={this.handleChange.bind(this)}

    Think about this

    function sum(a,b){
       return a+b;
    }
    
    const sumWithNoArgs = () => sum.bind(null, 1,2);
    

    If we now call sumWithNoArgs() we will get a new function instead of the sum. This is exactly what select does, it calls the function you are passing.

    You have to do

    const sumWithNoArgs = () => sum.bind(null, 1,2)();
    

    so we we call SumWithNoArgs() we get the propper result.

    You need to either make the binding of your function in the constructor or declare the function as a class variable so it's automatically bound to your class.