react-select - How can I filter the dropdown options between 2 Selects?

Viewed 2336

In react-select, when using the same array for both dropdown option choices, is it possible to remove one of the selected options if it has been selected in the other dropdown already?

I would like both dropdowns to show all 4 countries to begin with, but if one country is selected in one drop-down, then it shouldn't show in the other drop-down (unless removed from the original dropdown).

Really scratching my head on this one.

this.state.countries =

countries: [
  {
    label: "Italy",
    value: "Italy"
  },
  {
    label: "France",
    value: "France"
  },
  {
    label: "Belgium",
    value: "Belgium"
  },
  {
    label: "United Kingdom",
    value: "United Kingdom"
  }
];

Both selects:

<Select 
  options={countries}
  components={animatedComponents}
  isMulti
  closeMenuOnSelect={false}
  onChange={this.handleChange}
/>

<Select 
  options={countries}
  components={animatedComponents}
  isMulti
  closeMenuOnSelect={false}
  onChange={this.handleChange}
/>

Function to remove selected option so it can't be used in the other dropdown?

handleChange = (selectedOption) => {

};

This should not be possible: The options should be shared but can only be used once in each dropdown.

enter image description here

1 Answers

You need to use controlled mode in both Select components (to control the options value), then listen to the change event and filter the other options:

const Component = () => {
  const [options1, setOption1] = React.useState(options);
  const [options2, setOption2] = React.useState(options);

  return (
    <>
      <Select
        isMulti
        options={options1}
        onChange={(v1) => {
          setOption2(options.filter((o2) => !v1.includes(o2)));
        }}
      />
      <div style={{ height: 30 }} />
      <Select
        isMulti
        options={options2}
        onChange={(v2, a) => {
          setOption1(options.filter((o1) => !v2.includes(o1)));
        }}
      />
    </>
  );
};

Codesandbox Demo

Related