Aaquib
Aaquib

Reputation: 444

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

Upvotes: 2

Views: 5207

Answers (2)

Nhat Do
Nhat Do

Reputation: 1

Just use a state array to keep track of the checkboxes.

export default function SideMenus({ sideOpen, setSideOpen }) {
 const [checkList, setCheckList] = useState([]);

 function handleChange(val, idx) {
   let newList = [...checkList]; // copy old list
   newList[idx] = !checkList[idx]; // toggle specific checkbox
   setCheckList(newList);
 }
 return (
     <div className="row">
       {category.map((item, idx) => {
         return (
           <div className="col-sm-12 px-3 py-2">
             <Checkbox
               key={item.label}
               onChange={(val) => handleChange(val, idx)}
               checked={checkList[idx]}
             >
               {item.value}
             </Checkbox>
           </div>
         );
       })}
     </div>
 );
}

Upvotes: 0

Aaquib
Aaquib

Reputation: 444

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>
 );
}

Upvotes: 2

Related Questions