Dev01
Dev01

Reputation: 14129

Reorder multi select in react-select

I'm using react-select with the isMulti prop to allow users to select from a list of months (January-December). If the user selects the months out of order, I want the selected items to be reordered.

How can I reorder the selected items?

Here's a screenshot of what I want recorded:

enter image description here

Here's my code:

handleChange = (selectedOptions, action) => {
    selectedOptions.sort((a, b) => { // <=== THIS DOESN'T WORK
        return a.value - b.value;    // <=== THIS DOESN'T WORK
    });                              // <=== THIS DOESN'T WORK
    this.setState({selectedOptions});
    const {onSelectedOption} = this.props;
    onSelectedOption(selectedOptions);
};


render() {
    const {selectedOptions, options, error} = this.state;
    return (
        <div>
            <Select
                isMulti
                closeMenuOnSelect={false}
                value={selectedOptions}
                onChange={this.handleChange}
                options={options}
                isClearable={false}
                isSearchable={false}
                placeholder="Months..."
                classNamePrefix="react-select"
            />
            {error && <div className="alert alert-danger">{error}</div>}
        </div>
    );
}

Upvotes: 3

Views: 3191

Answers (1)

Laura
Laura

Reputation: 8630

You are really close from the solution except the way you compare the values is wrong:

selectedOptions.sort((a, b) => { 
  return a.value - b.value; --> this returns NaN
}); 

a and b values are both Strings so you should do:

selectedOptions.sort((a, b) =>
  a.value.localeCompare(b.value)
);

if you want to order them in alphabetically.

Upvotes: 2

Related Questions