Sorting in react-select

12,247

To achieve your goal you can use onChange props in order to reorder your options stored in state like this:

function compare(a, b) {
  return a.label > b.label ? 1 : b.label > a.label ? -1 : 0;
}

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      options: options
    };
  }

  onChange = newOptions => {
    // take original options and remove selected options
    const stateOptions = options.filter(
      option => !newOptions.find(op => op === option)
    );
    // sort the selected options
    const orderedNewOptions = newOptions.sort(compare);
    this.setState({
      // concat the two arrays
      options: orderedNewOptions.concat(stateOptions)
    });
  };
  render() {
    return (
      <Select
        isMulti
        hideSelectedOptions={false}
        options={this.state.options}
        onChange={this.onChange}
      />
    );
  }
}

You'll need to use hideSelectedOptions={false} to prevent selected options to be hidden.

Here a live example.

Share:
12,247

Related videos on Youtube

Zhirayr
Author by

Zhirayr

Updated on June 04, 2022

Comments

  • Zhirayr
    Zhirayr almost 2 years

    I'd like to know is it possible to make all selected options to appear at the top of the list, and then sort all selected options alphabetically? Or at least just make them to appear at the top. Thank you in advance.

    • coreyward
      coreyward over 5 years
      How would that work when you make a new selection? The list would re-order on-select, which would be rather unexpected and jarring for a user.
    • Zhirayr
      Zhirayr over 5 years
      If you have an option to make the option disappear from the list on select, you can make that option to appear in the top of the list instead.
    • coreyward
      coreyward over 5 years
      Oh so you want the select dropdown to close still, but when it's re-opened the selected items are at the top?
  • Sample Test
    Sample Test over 3 years
    how to do it on componentmount