How to create columns dynamically from data in antd?

Viewed 305

I want to create a reusable data table component using antd where columns create dynamically from data. How can I do that?

here is my code:

 const data= [
  {
    key: 1,
    name: 'Jack',
    email:'jack@gmail.com',
    address: 'Dhaka'
  },
  {
    key: 2,
    name: 'jon',
    email:'jon@gmail.com',
    address: 'Dhaka'
  }
];

const TableContainer = (props) => {
  const { columns, data, loading } = props;

  return <Table columns={columns} dataSource={data} loading={loading} />;
};

export default TableContainer;
1 Answers

You can conditionally render your table based on data.length as follows. If you have an empty array, then it won't show the table.

const TableContainer = (props) => {
  const { columns, data, loading } = props;

   return (
    <>{data?.length > 0 && <Table columns={columns} dataSource={data}  loading={loading} />}</>
  );
};
Related