Drsaud
Drsaud

Reputation: 425

How to define a max limit of options in react-select?

I created a react select component for my app react and I have more than 70 options, for that I want to define a max limit of options that the user can choose to handle it well. Can you please help me?

The code:

export default function ReactSelect(props) {
  const animatedComponents = makeAnimated();
  return (
    <Select
      isMulti="true" // allow to select mutli options
      isRtl="true" // right to left
      name="name" // html name
      options={accountsNames} // options
      className="basic-multi-select"
      classNamePrefix="select"
      isSearchable="true" // searchable for the closest one
      placeholder="اختر اسم الحساب..." // if there is no option selected
      components={animatedComponents}
    />
  );
}

Upvotes: 13

Views: 17932

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81410

You can control the selected options state and disable the options conditionally based on selectedOptions.length like this:

const [selectedOptions, setSelectedOptions] = React.useState([]);

return (
  <Select
    isMulti
    value={selectedOptions}
    onChange={(o) => setSelectedOptions(o)}
    options={colourOptions}
    // only allow user to choose up to 3 options
    isOptionDisabled={() => selectedOptions.length >= 3}
    className="basic-multi-select"
    classNamePrefix="select"
  />
);

Live Demo

Codesandbox Demo

Upvotes: 18

Harshit Rastogi
Harshit Rastogi

Reputation: 2122

This might help:

const MultiSelect = ({valueList, onChange, options, maxLimit = 5}) => {
  return (
    <Select
      value={valueList}
      isMulti
      onChange={onChange}
      options={options}
      isOptionDisabled={(option) => valueList.length >= maxLimit}
    />
  );
};

Upvotes: 3

Related Questions