2

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)

1
  • There is an easy way without changing the original data format. You can use getOptionLabel and getOptionValue props on React-Select. See this answer Commented Mar 27, 2021 at 8:01

1 Answer 1

2

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)}
                 />

Sign up to request clarification or add additional context in comments.

Comments

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.