You can create a state to store the keys of columns so we can filter out the columns. I make Checkbox.Group
as controlled component. When you change any checkbox value, in onChange function you will get an array of checkbox keys that are currently selected.
Hope this solve your problem.
import { useState } from 'react';
import { Checkbox, Table } from 'antd';
const columns = [
{ title: 'Name', dataIndex: 'name', key: 'name' },
{ title: 'Age', dataIndex: 'age', key: 'age' },
{ title: 'Cars', dataIndex: 'cars', key: 'cars' },
{ title: 'Bikes', dataIndex: 'bkes', key: 'bikes' },
{ title: 'Plane', dataIndex: 'plane', key: 'plane' },
{ title: 'Address', dataIndex: 'address', key: 'address' }
];
const dataSource = [
{ key: '1', name: 'Mike', age: 32, address: '10 Downing Street' },
{ key: '2', name: 'John', age: 42, address: '10 Downing Street' }
];
const columnsKeys = columns.map((column) => column.key);
const App = () => {
const [selectedColumns, setSelectedColumns] = useState(columnsKeys);
const filteredColumns = columns.filter((column) => selectedColumns.includes(column.key));
const onChange = (checkedValues) => {
setSelectedColumns(checkedValues);
};
return (
<>
<Checkbox.Group onChange={onChange} value={selectedColumns}>
{columnsKeys.map((column) => (
<Checkbox value={column} key={column}>
{column}
</Checkbox>
))}
</Checkbox.Group>
<Table dataSource={dataSource} columns={filteredColumns} />;
</>
);
};
export default App;