How to get the current Page Index of TantStack Table
Asked Answered
M

3

7

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>
Meggy answered 16/7, 2023 at 12:25 Comment(0)
T
14

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>

Transcendentalistic answered 12/8, 2023 at 13:21 Comment(1)
table.getState().pagination.pageIndex can be null or undefined, so your page will crashInae
T
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)
  }));
    
Theodore answered 2/8, 2023 at 17:38 Comment(0)
I
0

the issue is that: options?.state?.pagination?.pageIndex CAN be undefined, then page crashes.

SOLUTION:

Inside Component:

const currentPage: number = React.useMemo(()=> {
        const isUndefined: Boolean = (options?.state?.pagination?.pageIndex === undefined || options?.state?.pagination?.pageIndex === null);
        return isUndefined ? 0 : options?.state?.pagination?.pageIndex as number;
      }, [options?.state?.pagination?.pageIndex])

Inside: HTML

        <Box>
            Page number: {currentPage + 1} of {getPageCount()}
        </Box>
Inae answered 19/2, 2024 at 14:36 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.