Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-select change name of option fields from ({ value: '', label:''}) to ({ id: '', name:''})

Is there a way to change the fields of an option object?

From my BE API i get:

const items = [{ id: 1, name:'dropdown1'}, { id: 2, name:'dropdown2'}];

So now i have to remap the fields to value and label, it would have been nice if i could set those fields dynamically, maybe something like:

    <Select
      optionRemapping={{value: 'id', label: 'name'}}
      options={items}
    />

Or maybe i have missed a pattern on how people do this?

Doing the below feels a bit wrong.

items.map((item) => {
  return { value: item.id, label: item.name };
});
like image 964
user3711421 Avatar asked Feb 06 '19 17:02

user3711421


2 Answers

Use getOptionLabel and getOptionValue props.

<Select
  getOptionLabel={option => option.name}
  getOptionValue={option => option.id}
  options={items}
/>

example : https://codesandbox.io/s/kmoyw8q667

like image 64
Mohamed Ramrami Avatar answered Nov 07 '22 09:11

Mohamed Ramrami


You could achieve your mapping by doing the following and deconstructing your items :

<Select
    options={items.map(({ id, name }) => ({ value: id, label: name}))}
/>
like image 28
Treycos Avatar answered Nov 07 '22 10:11

Treycos