1

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.

4
  • 1
    i imagine the default value with be 'Test value' instead of an object Commented Mar 8, 2019 at 15:27
  • 1
    Try waiting to render your select element until your options have been fetched from the API. defaultValue may only select the option if it exists on the first render. Commented Mar 8, 2019 at 16:18
  • @Wex what should i use to wait for select to render like some sort of sleep statement ? sorry for stupid question but have never done anything like that in react. Commented Mar 9, 2019 at 16:54
  • Declarative style views are a pretty dramatic shift from their traditional imperative counterpart. Your application state drives the view, which should make your code more predictable and easier to debug. Commented Mar 9, 2019 at 19:35

1 Answer 1

1

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} />
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.