I'm using react-select
to create a Select option in my create-react-app
and am trying to map over an array of objects to generate the options. My app loads fine but when I click on the Select I get this error: Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {name}). If you meant to render a collection of children, use an array instead.
I'm passing the data to the component via props which is working fine, and the data is structured like this:
const guests = [
{
name: 'Kait',
plus: true,
plusName: 'Kitty'
},
{
name: 'Séanin',
plus: true,
plusName: 'Guest'
}
]
And here's the Select component:
<Select
value={selectedOption}
onChange={this.handleChange}
options={
this.props.guests.map((guest, index) => {
return {
label: guest,
value: guest,
key: index
}
})
}
/>
Any ideas on how I can fix this?
Sung M. Kim‘s answer is correct, but there is an easier way to use your attributes as label and value without remapping your options array.
Using the props getOptionLabel
and getOptionValue
you can keep your object mappings. Both accept a function that gets a single option as an argument and returns the value or label from the appropriate object property as string.
<Select
options={this.props.guests}
getOptionLabel={(option) => option.name}
{ /* Couldn't find a value in your structure, so I used name again */ }
getOptionValue=((option) => option.name}
{ ... }
/>
See documentation for more.
You probably will have to generate the array before rendering the component
const options = this.props.guests.map((guest, index) => {
return {
label: guest.name,
value: guest,
key: index
}
})
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
Edit:
is because you are passing an object in the label field. You should pass a String instead
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