Marko Marchisio
Marko Marchisio

Reputation: 497

Checkbox in antd table - how to save it while using pagination (React)

So im using Ant design's table component. I have also enabled checkboxes to be usable in the table.

The scenario that i want to achieve is this.

e.g. There is 10 pages of data in the table. User checks 3 items on the first page and then goes to the second page. There he checks 4 more items and then goes back to the first one. When he goes back to the first one the first 3 items he selected are still checked (blue checkmark) which gives to a total of 7 items checked.

How to achieve this?

This is my the Pagination component

<Pagination
        current={pageNumber}
        pageSize={pageSize}
        pageSizeOptions={[10, 20, 50, 100]}
        onChange={(e) => {
          setTriggerPage(!triggerPage);
          setPageNumber(e);
        }}
        total={totalCardCount}
        locale={{ items_per_page: "/ stranica" }}
        className="mt20"
        showLessItems={true}
        hideOnSinglePage={false}
        onShowSizeChange={(e, size) => setPageSize(size)}
        showSizeChanger={true}
      />


This is the table component

<Table
        rowSelection={rowSelection}
        dataSource={data}
        pagination={false}
        loading={loading}
        rowKey={"id"}
        style={{ cursor: "pointer" }}
        scroll={{ y: 400 }}
      >

This is the row selection property of the table

  const rowSelection = {
    selectedRowKeys: selectedRow.map((row) => row.id),
    onSelectAll: (selected, selectedRows) => {
      setSelectedRow(selectedRows);
    },
  };

Upvotes: 1

Views: 3146

Answers (2)

Harshad M
Harshad M

Reputation: 41

Pass preserveSelectedRowKeys to true as a prop to preserve the data with pagination.

 rowSelection={{
          type: "checkbox",
          preserveSelectedRowKeys: true,
          ...rowSelection,
       }}

Upvotes: 4

Shayan Faghani
Shayan Faghani

Reputation: 240

Because you are using Pagination in AntD, you can simply create a state object (as an object with the key value of the page number for example) and then add the selectedRows inside as an array. So anytime you need to render your table you can read the values of the checkboxes from the state and then show the checked option.

if you need to see the total number of selected elements you can simply manipulate the states you have to see the total number, or if you are showing this in other components and pages, you need to use the context.

Upvotes: 0

Related Questions