Can one control the state of Antd Table's "Check All" control?

Viewed 8715

I have an Ant Design table with sorting, selection and pagination. By default (if I understand it correctly), Antd Table selection works on a per-page basis. If you click the 'Select All' checkbox in the selection column header, Antd will select all the rows on the current page but if you then change page, both the rows and header will revert to a unchecked state. The selection is not lost because if you then go back to the previous page, the rows and header are all checked.

So I wanted to change this so that 'Select All' really selects all the rows of the table regardless of pagination. I found a few github issues in which recommended simply managing the selectedRowKeys array onSelect and onSelectAll functions oneself. I did this and now my selection works as expected...

However...

The "select all" checkbox in the selection column header still functions in terms of the page rows. So for example if I'm on the first page and "Select all" then deselect one of the rows, the "select all" checkbox is in the intermediate/partial state as expected. However if I then go to the next page, all rows are checked as expected and so is the "select all" checkbox in the header. For this selection to make sense functionally it would need to remain in the intermediate/partial state. It needs to reflect the selection over the entire dataset and not just the current page.

This can be seen in this simple example : https://codesandbox.io/s/antd-table-selection-ikqym

Any ideas how to override the "select all" checkbox ?

Cheers

3 Answers

There is a new property called preserveSelectedRowKeys in TableRowSelection that allows to preserve the selected row keys:

const rowSelection: TableRowSelection<CustomClass> = {
        preserveSelectedRowKeys: true,
        selectedRowKeys,
        onChange: this.onSelectChange,
};

onSelectChange = (selectedRowKeys: Key[], selectedRows: CustomClass[]) => {
    this.setState({ selectedRowKeys, selectedElements: selectedRows });
};

You can achieve this effect via the rowSelection prop on the Table component. You will need to programatically set selectedRowKeys within the onSelectAll event handler to select/deselect all Table rows instead of just the rows on the active page.

Please see the CodeSandbox example below for a working example of your use case: https://codesandbox.io/s/antdtableselectallrows-bzisr?file=/index.js

Happy Coding!

Related