Home > OS >  Hide column if there is no data in ant design table
Hide column if there is no data in ant design table

Time:01-20

I am looking for a way to hide a column if we don't have data for a particular column. is it possible to hide the column if the column has no data? I am getting the data from server. please refer this image For this table, I don't have data in 'Sports' column, so I want this column to be hidden.

{
title: ‘id’,
dataIndex: ‘id’,
},
{
title: ‘Name’,
dataIndex: ‘empName’,
},
{
title: ‘Age’,
dataIndex: ‘empAge’,
},
{
title: ‘Sports’,
dataIndex: ‘sports’,
},
{
title: ‘Fruits’,
dataIndex: ‘fruits’,
},
{
title: ‘Colors’,
dataIndex: ‘colors’,
},

CodePudding user response:

    let columns = [{
title: ‘id’,
dataIndex: ‘id’,
},
{
title: ‘Name’,
dataIndex:‘empName’,
},
{
title: ‘Age’,
dataIndex: ‘empAge’,
},
{
title:‘Sports’,
dataIndex: ‘sports’,
},
{
title: ‘Fruits’,
dataIndex: ‘fruits’,
},
{
title: ‘Colors’,
dataIndex: ‘colors’,
},
].filter(item => !item.hidden);

CodePudding user response:

You can write a method, e.g. "getColumnData", and provide that method to your antd component.

<Table dataSource={data} columns={getColumnData()} />

Inside that getColumnData, you could cycle through your data, and either return a column object, or not.

E.g.:

const getColumnData = () => {
 // data should be a state variable, so that <Table /> re-renders if data changes
 return data.map((dataSet) => {
 // cycle through each dataSet and check if data exists
 // If thats the case, return a column object for the table
   if (dataSet.data.length > 0) {
     return {
      title: dataSet.name,
      dataIndex: dataSet.key,
      key: dataSet.key,
     };
   }
 });
};

If your dataSet "sports" does not have any data, the map function wont return a column object, and thus your antd Table wont show that column.

  • Related