user3711421
user3711421

Reputation: 1808

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

Upvotes: 16

Views: 25050

Answers (2)

Mohamed Ramrami
Mohamed Ramrami

Reputation: 12701

Use getOptionLabel and getOptionValue props.

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

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

Note: It's generally a good idea to create those functions outside your component to keep the reference stable and avoid unnecessary re-renders of your Select.

Upvotes: 42

Treycos
Treycos

Reputation: 7492

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

<Select
    options={items.map(({ id, name }) => ({ value: id, label: name}))}
/>

Upvotes: 4

Related Questions