Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate options by mapping over array of objects with react-select

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?

like image 815
kait Avatar asked Jan 27 '23 14:01

kait


2 Answers

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.

like image 199
Rallen Avatar answered Jan 29 '23 04:01

Rallen


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

like image 36
Yiyo Avatar answered Jan 29 '23 03:01

Yiyo