I want to give the user an option to hide or show columns of Antd table via a group of checkboxes. I tried different online solutions but I didn't succeed. I want something like this, as in the below picture.
note: some columns has been checked by default, but user can also uncheck them
I am stuck with this problem from last 2 days. Here is my code.Thanks in advance!
https://stackblitz.com/edit/react-h8hoys-q2mfxy?file=demo.js
CodePudding user response:
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;
CodePudding user response:
I changed your code in 3 point:
- I used
setState
instead of regular variables (likeconst
) - I initialized state by
baseColumns
filtering for hide cars column (because it was checked at by default). - I changed
onChange
function for filterbaseColumns
and pass it tosetColumn
:
const baseColumns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Cars',
dataIndex: 'cars',
key: 'cars',
},
{
title: 'Bikes',
dataIndex: 'bikes',
key: 'bikes',
},
{
title: 'Plane',
dataIndex: 'plane',
key: 'plane',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
];
let [columns, setColumns] = useState(
baseColumns.filter((item) => item.dataIndex !== 'cars')
);
let onChange = (checkedValues) => {
console.log(checkedValues);
setColumns(
baseColumns.filter((item) => !checkedValues.includes(item.dataIndex))
);
};