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?
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.
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.
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
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With