Get react-select selected option when using multi dropdown

Uciebila picture Uciebila · Nov 7, 2018 · Viewed 18k times · Source

I have two working react-select drop downs on my page, one that allows the user to select A or B, and one that allows them to choose multiple items from "blue, yellow , red".

When they have chosen these items, I want to use them. For now I just want to check the values that have been selected, so I'm just printing them to screen. For the single selection drop down I have used the example code from the github successfully. This is as follows:

import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'a', label: 'a' },
  { value: 'b', label: 'b' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    document.write(`Option selected:`, selectedOption.value); //this prints the selected option
  }
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
        //isMulti //added when the user can pick more than one
      />
    );
  }
}

My question is how do I successfully do this for the multi option? The user can select as many as they wish, but an 'undefined' error is thrown when it prints the option that has been selected. I think this is because the option is stored in an array but I'm not sure.

Thanks all.

Answer

Colin Ricardo picture Colin Ricardo · Nov 7, 2018

You need to change the handleChange to deal with the isMulti. Here's an example:

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

const options = [
  { value: 'a', label: 'a' },
  { value: 'b', label: 'b' },
];

class App extends React.Component {
  state = {
    selectedOptions: [],
  }

  handleChange = (selectedOptions) => {
    this.setState({ selectedOptions });
  }

  render() {
    const { selectedOptions } = this.state;

    return (
      <React.Fragment>
        <Select
          isMulti
          value={selectedOption}
          onChange={this.handleChange}
          options={options}
        />
      {selectedOptions.map(o => <p>{o.value}</p>)}
      </React.Fragment>
    );
  }
}

render(<App />, document.getElementById('root'));

Here's a working example: https://stackblitz.com/edit/react-czf4ib