Home > Software design >  How to Limit React Multi-Checkbox Item Selection
How to Limit React Multi-Checkbox Item Selection

Time:11-01

This is my checkbox components for multi selection.

const MultiselectCheckbox = ({ options, onChange, limitedCount }) => {
  const [data, setData] = React.useState(options);

  const toggle = index => {
    const newData = [...data];
    newData.splice(index, 1, {
      label: data[index].label,
      checked: !data[index].checked
    });
    setData(newData);
    onChange(newData.filter(x => x.checked));
  };

  return (
    <>
      {data.map((item, index) => (
        <label key={item.label}>
          <input
            readOnly
            type="checkbox"
            checked={item.checked || false}
            onClick={() => toggle(index)}
          />
          {item.label}
        </label>
      ))}
    </>
  );
};

const options = [{ label: 'Item One' }, { label: 'Item Two' }];

ReactDOM.render(
  <MultiselectCheckbox
    options={options}
    onChange={data => {
      console.log(data);
    }}
  />,
  document.getElementById('root')
);

I want to limit the items I can choose by putting limitedCount in my code. props for example

  • limitedSelectCount = 1
    • Only one check box can be selected
  • limitedSelectCount = n
    • Multiple n check boxes available

CodePudding user response:

its very easy just put a condition in your toggle function to check if the length of data array is not greater or equal to the limitedCount. Also check if the limitedCount prop has been passed to the component or not.

const toggle = index => {
    
    // add the below line to your code
    if(limitedCount && data.length>=limitedCount) return;

    const newData = [...data];
    newData.splice(index, 1, {
      label: data[index].label,
      checked: !data[index].checked
    });
    setData(newData);
    onChange(newData.filter(x => x.checked));
  };

  • Related