Xena
Xena

Reputation: 377

How to use react-select with api

I use react-select as a dropdown for autosearch import the library and render component:

<Select
              className='search-line'
              placeholder='Search...'
              options={dataList}
              onChange={opt => console.log(opt)}
                 />

The problem is that options is data that comes from API as an array of objects :

const data = [
  { id: 1,
    name: 'Bmw'
  },
  { id: 2,
    name: 'Ferrary'
      }
]

but to render options react-select requires objs with such key-val as

const options = [
    { value: name, label: name}
]

How to loop through my array and change that value and label obj key-val ?

This works but it splits all the names I have in array of objects I fetch from API:

   const name  = data.map(i => {
     return i.name
   })

  const dataList = [
    { label: name, label: name}
  ]

Data - is a prop with data (array of objects fetched from API)

Upvotes: 2

Views: 2973

Answers (1)

srosser2
srosser2

Reputation: 111

You can use

const options = data.map(item => {
    return {
        label: item.name,
        value: item.id     
    }
}

console.log(options) // [{ label: 'Bmw', value: 1}, { label: 'Ferrary', value: 2 }]


<Select
              className='search-line'
              placeholder='Search...'
              options={options}
              onChange={opt => console.log(opt)}
                 />

Upvotes: 2

Related Questions