Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set defaultValue for multi select?

Tags:

react-select

So, I need to pass defaultValue to a react-select component with enabled multi select. I've tried everything I could think of: array of strings, array of objects, string, etc... Nothing seems to work.

I'm also using the getOptionLabel and getOptionValue, might they be the cause for all this mess?

like image 346
SamJust Avatar asked Nov 15 '18 10:11

SamJust


3 Answers

defaultValue accepts an object or array of objects. here an object can be like this :

defaultValue = {{ value: 0, label: "John" }}

This is also one way:

defaultValue = { array1[0] }

If you want array of objects for multiple options (isMulti) you can do this:

defaultValue = { array1.map(ele => ele) }

Where array1 is an array of objects.

array1 = [
    { label: "John", value: 0 },
    { label: "Indiana", value: 1 },
    { label: "Stark", value: 2 },
];

This solution worked for me. I hope this helps you too.

like image 147
Rutuja Dhokchaule Avatar answered Sep 30 '22 16:09

Rutuja Dhokchaule


If you refer to react-select documentation, the way to set defaultValue to multiple value select:

<Select
    defaultValue={[colourOptions[2], colourOptions[3]]}
    isMulti
    name="colors"
    options={colourOptions}
    className="basic-multi-select"
    classNamePrefix="select"
/>

The structure of options is

[ 
  {
      label: <string>,
      value: <string>,
    } 
]

Working example here.

like image 22
Laura Avatar answered Sep 30 '22 16:09

Laura


There is an alternate way to use value as your defaultValue. In my case I have used "id" and "industry" instead of "label" and "value"

this.state = {
     interested_industries: [{id:"ANY", industry:"ANY"}]
}

And in Select component:-

<Select 
    name="interested_industries"
    options={industries}
    value={interested_industries}
    getOptionLabel={ x => x.id}
    getOptionValue={ x => x.industry}
    onChange={this.handleSelect}
    isMulti
/>
like image 33
Tron Avatar answered Sep 30 '22 17:09

Tron