Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Select custom options array?

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
                    />
like image 772
Mike Vlad Avatar asked Dec 08 '22 12:12

Mike Vlad


2 Answers

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

like image 197
Agney Avatar answered Dec 11 '22 11:12

Agney


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];
    ...
}
like image 24
Johan Malan Avatar answered Dec 11 '22 11:12

Johan Malan