hankdoupe
hankdoupe

Reputation: 41

How to disable `deselect-option` in `react-select`?

I would like to use the react-select multi Select component and be able to select the same option multiple times. However, react-select does not allow one to do this. You can change the dropdown to show already selected options with hideSelectOptions={false}, but if you select one of them again, it will be deselected.

This issue #3234 describes this same problem and sugggests that one way to solve this problem is to handle the action argument to onChange somehow.

Here is the solution that I attempted based off of the suggested solution:

import React, { Component } from "react";
import Select from "react-select";


export default class MultiSelect extends Component<*, State> {
  handleChange(option, action) {
    console.log(option, action);
    // return;
    if (action === "deselect-option") {
      action = "select-option";
      // now how do I do the component's state?
    }
  }

  render() {
    return (
      <Select
        isMulti
        className="basic-single"
        classNamePrefix="select"
        name="color"
        options={[{"label": "hello", "value": "hello"}, {"label": "world", "value": "world"}]}
        hideSelectedOptions={false}
        onChange={this.handleChange}
      />
    );
  }
}

I expected to be able to enter "hello" multiple times but when I tried to enter "hello" again it was deleted.

Upvotes: 4

Views: 5864

Answers (1)

Prasoon David
Prasoon David

Reputation: 11

In options, the data field makes value dynamic with any key, in this case, use Date.now() to make dynamic. then use actions 'select-option' to append to options, use actions 'remove-value'' to filter all fields in the Options data field with a label matching with selected option label and append to data and append one more object to Options datafield

options = [
{ value: Date.now(), label: "SUBJECT" ,val:"SUBJ" },
{ value: Date.now, label: "VERB", val:"VERB" }
]

<Select options={options} isMulti onChange={(e, option) => {
if (option.action === "select-option") {
    Options=[
    ...Options,
    {
        value: option.option.value + "_" + Date.now(),
        label: option.option.label
    }
    ];
} else if (option.action === "remove-value" ||option.action ===  "pop-value") {

    tempData = data.filter(opt => opt.label !== option.removedValue.label)
    Options=[
    ...tempData,
    {
        value: option.removedValue.value + "_" + Date.now(),
        label: option.removedValue.label
    }
    ]
}
}
} />

Upvotes: 1

Related Questions