I'm learning react and have come across react-select
behaviour which i'm unable to understand.
I've a react-select
component whose values are being fetched from an api call. If I use defaultValue
then it doesn't select that value from dropdown but if i use value
then it selects value for the dropdown.
I'm just confused why defaultValue
is not working.
<Select
key={`dropdown`}
options={options}
onChange={onSelect}
defaultValue={defaultValue} />
where 'options' are being passed as props from other component where they are being fetched from an api call.
defaultValue
is also being passed as prop and have structure like this:
defaultValue = {
label: `Test label`,
value: `Test value`
}
But now if I change the select component like
<Select
key={`dropdown`}
options={options}
onChange={onSelect}
value={defaultValue} />
Now it works fine.
So what is the difference value
and defaultValue
. Why the defaultValue
is not able to set the option in react select.
You should delay rendering your <Select>
element until your API has returned the options
data. Here's one approach that may work for you:
/* options is null/undefined until API sets value to an array */
renderSelect(options) {
if (options == null) return null;
return <Select
key={`dropdown`}
options={options}
onChange={onSelect}
value={defaultValue} />
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.