marielle
marielle

Reputation: 438

react-select: disable dropdown list

Is there a way to disable the dropdown list? I didn't find any props that can help me.

In particular, I would like to disable the dropdown list when user has selected more than 5 elements.

I created this codesandbox. It doesn't really work because it's not linked to a state:

const limit = 3;
const defaults = [colourOptions[2], colourOptions[3]];

export default () => (
  <Select
    defaultValue={defaults}
    isMulti
    name="colors"
    options={colourOptions}
    className="basic-multi-select"
    classNamePrefix="select"
    isSearchable={defaults.length < limit}
    // disableDropdown={defaults.length > limit} // <-- something like this
  />
)

Upvotes: 3

Views: 8690

Answers (2)

Shubham Verma
Shubham Verma

Reputation: 5054

You can simply do this. Basically track how many elements are already set. Then isOptionDisabled from re-select disable option if option length is greater than limit:

import React, { useState } from "react";
import Select from "react-select";
import { colourOptions } from "./docs/data";

const limit = 3;
const defaults = [colourOptions[2], colourOptions[3]];
// console.log(defaults);
export default () => {
  const [options, setOptions] = useState(defaults);
  return (
    <Select
      defaultValue={defaults}
      isMulti
      name="colors"
      options={colourOptions}
      onChange={(val) => setOptions(val)}
      className="basic-multi-select"
      classNamePrefix="select"
      isSearchable={defaults.length < limit}
      isOptionDisabled={(option, test) => options.length > limit} // <-- something like this
    />
  );
};


Here is the demo: https://codesandbox.io/s/relaxed-feistel-w44ns?file=/example.js:0-675

Upvotes: 3

0stone0
0stone0

Reputation: 43972

You can 'disable/remove' the dropdown by removing the components;

components={{
    Menu: () => null,               // Remove menu
    MenuList: () => null,           // Remove menu list
    DropdownIndicator: () => null,  // Remove dropdown icon
    IndicatorSeparator: () => null  // Remove separator
}}
<Select
    defaultValue={defaults}
    isMulti
    name="colors"
    options={colourOptions}
    className="basic-multi-select"
    classNamePrefix="select"
    isSearchable={defaults.length < limit}
    components={{
        Menu: () => null,
        MenuList: () => null,
        DropdownIndicator: () => null,
        IndicatorSeparator: () => null
    }}
/>

Updated code-sandbox

Documentation

Upvotes: 7

Related Questions