I am getting an array of flavors from my backend.
This is my jsx:
<div className="mb-3">
<Select options={flavorOptions} onChange={onSelectOption} value={flavor} />
</div>
The array is being formatted to the correct format needed for react-select, like this:
const flavorOptions =
[
flavors.map(f => {
return {
value: f, label: f
}
})
]
This is my onSelectOption function:
const onSelectOption = (option) => {
const copy = {...order}
copy.flavor = option.value
setOrder(copy)
}
This is the output
and when I click on that one option (that isn’t even visible), the first option shows up but when onChange calls the onSelectOption function the whole array gets sent in.
So really my question has three parts:
- Why is only one option showing up?
- Why isn’t it visible?
- Why is the whole array getting passed to the onSelectOption function, as opposed to just the selected value?
I tried adding these props – getOptionLabel={option => option.label} getOptionValue={option => option.value}
to Select and got the same results.
I also tried this:
<Select>
{flavorOptions.map(flavor => {
<option key={flavor.label} value={flavor.value} > {flavor.label}</option>
})}
</Select>
which resulted in getting the No options message.
If anyone has any idea what I might be doing wrong, I would greatly appreciate feedback.
I am very new to react, and programming in general so it could very well be a careless mistake.
2
Answers
Based on your code snippets, it seems that the issue lies in the way you’re formatting the flavorOptions array.
Currently, you are wrapping the flavors.map() function inside an array, which results in a nested array. This is causing the Select component to receive an array as its options prop, instead of an array of objects.
To fix this, you can remove the square brackets around flavors.map() so that the flavorOptions array is not nested:
Regarding your questions:
Here’s the updated code:
Make sure to check for any other potential issues such as missing imports or incorrect variable values.
Just remove the square brackets here:
What you passed in was like
[["apple", "banana"]]
when you just need["apple", "banana"]
Stackblitz: https://stackblitz.com/edit/stackblitz-starters-wrswve?file=src%2FApp.tsx