1

I am working on building a table using TantStack and React Table libraries. I want to display the current page index in the table footer, something like "Page 1 of 8," where "1" represents the current page number, and "8" is the total number of pages. I am having trouble figuring out how to access the current page index from the TantStack table state.

It should be placed between those buttons:

<Button
          variant="outline"
          size="sm"
          onClick={() => table.previousPage()}
          disabled={!table.getCanPreviousPage()}
        >
          Previous
        </Button>
        <Button
          variant="outline"
          size="sm"
          onClick={() => table.nextPage()}
          disabled={!table.getCanNextPage()}
        >
          Next
        </Button>
hantoren
  • 357
  • 2
  • 17

2 Answers2

2

It's much simpler than this. just state this in the bottom of the table: <strong>{table.getState().pagination.pageIndex + 1} of{" "} {table.getPageCount()}</strong>

steve123
  • 31
  • 3
1

You need to store the page index in a state variable and also pass the setState method to tanstack table to set the current page index. You can try the following code:

  const [state, setState] = useState(table.initialState);

  const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10
  });

  const pagination = useMemo(
    () => ({
      pageIndex,
      pageSize
    }),
    [pageIndex, pageSize]
  );

  // override the state managers for the table
  table.setOptions(prev => ({
    ...prev,
    onStateChange: setState,
    state: {
      ...state,
      pagination,
    },
    onPaginationChange: setPagination,
    pageCount: Math.ceil(numOfRows / pageSize)
  }));
    
Bipin MV
  • 51
  • 3