I'm trying to use react-select, https://react-select.com/, and the mandatory format for the options prop seems to be {value:something, label:something}.
I have a list of objects with other key,value pairs and my question is if there is any workaround for me not having to modify the array because if i modify it, it means that the select component will not return an object of the initial array so i will have to map them again.
options = [
    {name: 'opt1', descr:'descr1'},
    {name: 'opt2', descr:'descr2'},
    {name: 'opt3', descr:'descr3'},
]
In Vue i get to choose the key that will be used as label, for example.
Vue:
:items="options.name"
In react i would have to do something like:
this.new_options = []
this.options.forEach(element => {
    this.new_options.push({
        value : element.name,
        label : element.name,
    })
})
And in Select:
                  <Select
                        name="selectedWires"
                        //closeMenuOnSelect={false}
                        components={makeAnimated()}
                        onChange={this.handleSelectChange('selectedWires')}
                        options={this.new_options}
                        isMulti
                    />
                With react-select you can map options with:
const options = [
  { val: 'chocolate', desc: 'Chocolate' },
  { val: 'strawberry', desc: 'Strawberry' },
  { val: 'vanilla', desc: 'Vanilla' }
]
<Select
  options={options}
  getOptionLabel={(option)=>option.desc}
  getOptionValue={(option)=>option.val}
/>
Docs
Live Demo
You could use the index as the value, then just get the original array element in the handleChange function.
<Select 
    name="selectedWires"
    options={this.options.map((option, idx) => ({
        value: idx,
        label: option.name
    }))} 
    onChange={(selection, action) => this.handleChange(selection, action)}/>
Then in the handle function:
handleChange(selection, action) {
    let selectedOption = this.options[selection.value];
    ...
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With