Home > Blockchain >  Dynamic Checkbox with antd
Dynamic Checkbox with antd

Time:12-15

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

CodePudding user response:

This is a basic example, which can give you more control

const data = [
  {
    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 App: React.FC = () => {
  const [items, setItems] = useState(data);

  const onChange = (item: any, e: CheckboxChangeEvent) => {
    console.log(`checked = ${e.target.checked}`, item);
    const checked = e.target.checked;
    setItems((checks) => {
      return checks?.map((e) => (e.id === item.id ? { ...e, checked } : e));
    });
  };

  return (
    <>
      {items.map((item, i) => {
        return (
          <div key={i}>
            <Checkbox
              checked={item.checked}
              onChange={(e) => onChange(item, e)}
            >
              {item.title}
            </Checkbox>
          </div>
        );
      })}
    </>
  );
};

Hope it helps

CodePudding user response:

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.filter(e => e.id !== item.id), { ...item, checked: !item.checked }]);

  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

  • Related