Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select: Limit number of selected options

Tags:

select

antd

I'm using ANT Design's Select component in multiple select mode. After two options are selected (see screenshot) I'd like to prevent any more from being selected. The field should not be disabled, so that you can deselect an option and select another.

I've tried the onFocus event, but it doesn't provide an event that I could use to preventDefault or otherwise keep from opening the dropdown. I've also tried adding a ref and calling blur() whenever the onFocus event is called. This closes the dropdown, but it's still visible for a second.

Does anyone know of a way to accomplish this?

enter image description here

like image 644
Mike Wheaton Avatar asked Jan 25 '23 07:01

Mike Wheaton


2 Answers

If 3 or more options selected then with a simple condition you can disable other options.

Store selected options in state and while displaying options disable them based on condition.

https://codesandbox.io/s/happy-leftpad-lu84g

Sample code

import React, { useState } from "react";
import { Select } from "antd";

const { Option } = Select;

const opts = ["a11", "b12", "c13", "d14", "e15"];

const Selectmultiple = () => {
  const [optionsSelected, setOptionsSelected] = useState([]);

  const handleChange = value => {
    console.log(`selected ${value}`);
    setOptionsSelected(value);
  };
  return (
    <div>
      <Select
        mode="multiple"
        style={{ width: "100%" }}
        placeholder="Please select"
        onChange={handleChange}
      >
        {opts.map(item => (
          <Option
            disabled={
              optionsSelected.length > 1
                ? optionsSelected.includes(item)
                  ? false
                  : true
                : false
            }
            key={item}
          >
            {item}
          </Option>
        ))}
      </Select>
    </div>
  );
};
like image 75
Hemanthvrm Avatar answered Feb 27 '23 04:02

Hemanthvrm


I solved this problem using "open" prop:

const isMaxValues = value.length === limit;

<Select
   mode="multiple"
   disabled={false}
   {...(isMaxValues && { open: false, onDropdownVisibleChange: handleShowError })}
>
   {renderOptions()}
</Select>

So you still able to remove/deselect some options

Also you can provide isMaxValues option to renderOptions method and disable Options to be selected(if you need dropdown to be visible)

like image 45
Andrey Getman Avatar answered Feb 27 '23 05:02

Andrey Getman