JedWatson / react-select

The Select Component for React.js
https://react-select.com/
MIT License
27.56k stars 4.12k forks source link

Get Label of selected option #623

Closed BattleSlug closed 4 years ago

BattleSlug commented 8 years ago

Hello, in my project options label is fully consistent name of an option, and this name should be rendered somewhere else upon selecting. But after selecting, onChange handler gets only options value, so to get label from it I have to make additional search in the array of options, which looks quite redundant. Is there any chance to get not only value, but also label with onChange? Maybe there is some separate method or undocumented feature for that? Thank you.

damassi commented 8 years ago

A way around this is to set multi to true, but then forbid more than one item from rendering.

clinyong commented 8 years ago

@damassi Could you give an example?

damassi commented 8 years ago

@clinyong - here you go -- I put this together in a hacky way and it has some project specific stuff, but hopefully you can use something from it:

import React, { Component } from 'react'
import Select from 'react-select'

export default class MultiSelect extends Component {

  render() {
    const {
      loadOptions, // async
      options, // sync
      value,
      onBlur,
      onChange,
      ...props
    } = this.props

    const SelectComponent = loadOptions
      ? Select.Async
      : Select

    const optionsType = loadOptions
      ? { loadOptions }
      : { options }

    return (
      <SelectComponent
        {...props}
        {...optionsType}
        multi
        value={value}
        className={this.props.max === 1 ? 'Select--multi-max1' : ''}
        onBlur={() => {}}
        onChange={(items) => {
          const { max } = this.props

          // Hack to get around React Selects inability to pass single items with values
          // and labels. Might be fixed after beta is out.
          if (!max) {
            return onChange(items)
          } else if (max && items.length <= max) {
            return onChange(items)
          }
        }}
      />
    )
  }
}
vnallamhawk commented 6 years ago

Hi @damassi ,

I am facing the same issue. Could you help with a sample that has some values in the dropdown.

damassi commented 6 years ago

@vnallamhawk - i've been away from this work for a while, so what's posted above is probably the best I can do. Hope you figure it out!

jossmac commented 4 years ago

Version 1 of react-select is no longer supported.

In the best interest of the community we've decided to spend the time we have available on the latest version.

We apologise for any inconvenience.

Please see:

  1. v1 to v2 upgrade guide
  2. v1 documentation and examples