Search code examples
javascriptreactjstypescriptantd

Dynamic Checkbox with antd


I have a data and want to create checkboxes.

By default all fields should be checked and when I will uncheck one of the filed I should know which one is uncheked and update the filter data (remove unchecked field).

I'm using the ordinary checkbox but here I cant know which checkbox is checked or not.

I tried with checkboxgroup too but in the checkboxgroup you should define Here is the Code example.

https://codesandbox.io/s/check-all-antd-5-0-7-forked-8bm54o?file=/demo.tsx

Solution

  • The easiest way is to add a checked property to your data object, and use it instead of Checkbox's one, so simply import useState() from React and do as following:

    import React, { useState } from "react";
    import "./index.css";
    import { Checkbox } from "antd";
    
    const App: React.FC = () => {
      const [data, setData] = useState<any[]>([
        {
          id: 0,
          title: "User ID",
          key: "userId",
          checked: true
        },
        {
          id: 1,
          title: "Description",
          key: "description",
          checked: true
        },
        {
          id: 2,
          title: "Surname",
          key: "surname",
          checked: true
        },
        {
          id: 3,
          title: "Name",
          key: "name",
          checked: true
        }
      ]);
    
      const onChange = (item) =>
        setData(data.map(e => e.id === item.id ? { ...e, checked: !item.checked } : e));
    
      return (
        <>
          {data.map((item) => (
            <Checkbox
              key={item.id}
              checked={item.checked}
              onChange={() => onChange(item)}
            >
              {item.title}
            </Checkbox>
          ))}
        </>
      );
    };
    
    export default App;
    

    Note that it's better to use your data's id as key in map() instead of map()'s index if you need to sort or modify your checkboxes' order, see more here