reactjsant-design-pro

How to checked only single checkbox from group of checkboxes in ant design?


I am using Antdesign checkBox to make a section of the filters where users can select different parameters to show data.


const category = [
  { label: "Gardening", value: "Gardening" },
  { label: "Plants", value: "Plants" },
  { label: "Seeds", value: "Seeds" },
  { label: "Bulbs", value: "Bulbs" },
  { label: "Planters", value: "Planters" },
];

export default function SideMenus({ sideOpen, setSideOpen }) {
 
  return (
      <div className="row">
        {category.map((item) => {
          return (
            <div className="col-sm-12 px-3 py-2">
              <Checkbox key={item.label}>
                {item.value}
              </Checkbox>
            </div>
          );
        })}
      </div>
  );
}

enter image description here


Solution

  • In order to check a single checkbox from a group of checkboxes, you have to pass value prop to get value, onChange prop to capture the value, and checked prop to check only that selected single value.

    const category = [
     { label: "Gardening", value: "Gardening" },
     { label: "Plants", value: "Plants" },
     { label: "Seeds", value: "Seeds" },
     { label: "Bulbs", value: "Bulbs" },
     { label: "Planters", value: "Planters" },
    ];
    
    export default function SideMenus({ sideOpen, setSideOpen }) {
     const [value, setValue] = useState("");
    
     function handleChange(checkedValues) {
       setValue(checkedValues.target.value);
     }
     return (
         <div className="row">
           {category.map((item) => {
             return (
               <div className="col-sm-12 px-3 py-2">
                 <Checkbox
                   key={item.label}
                   onChange={handleChange}
                   checked={item.value == value}
                   value={item.value}
                 >
                   {item.value}
                 </Checkbox>
               </div>
             );
           })}
         </div>
     );
    }