Thanasis Ioannidis
Thanasis Ioannidis

Reputation: 3231

How can I work with just values in react-select onChange event and value prop?

I try to use react-select in my reactjs app, but I have a problem with the onChange event. onChange is supposed to send two arguments. The first is supposed to be the selected value, but instead of the selected value, the whole option item is passed as the selected value.

For instance

This behavior is inconsistent with most input components out there. I would expect onChange to be passed the value of the item, and for the item itself I would expect another event like onItemSelected or something like that.

Also, when I set value={'2'} (controlled component), the component doesn't show the selected item.

I must say that I use AsyncSelect with loadOptions.

How can I make it work with just simple values, instead of option objects?

If this can't happen I have to abandon react-select for another similar component.

Upvotes: 4

Views: 5902

Answers (1)

Andrea Rosales
Andrea Rosales

Reputation: 1058

AFAIK currently there's no way to make React-Select work internally with just the value. What I'm doing in my application is implementing a layer to retrieve the object going down, and extract the value going up. Something like this (this is simplified, you may need more validation or handling depending on your application):

const Select extends Component {
  handleChange(newSelected) {
    // this.props.handleChange is your own function that handle changes
    // in the upper scope and receives only the value prop of the object
    // (to store in state, call a service, etc)
    this.props.handleChange(newSelected.value);
  }

  render() {
    // Assuming you get the simple value as a prop from your store/upper 
    // scope, so we need to retrieve the option object. You can do this in 
    // getDerivedStateFromProps or wherever it suits you best
    const { options, value } = this.props;
    const selectedOption = options.find(option => option.value === value)

    <ReactSelect
      options={options}
      value={selectedOption}
      onChange={this.handleChange}
      {...props}
    />
}

Upvotes: 5

Related Questions