search

Home  >  Q&A  >  body text

How to get the current Page Index of the TantStack table

<p>I'm building a table using TantStack and the React Table library. I want to display the current page index in the table footer, like "Page 1 of 8", where "1" means the current page number and "8" is the total number of pages. I can't figure out how to access the current page index from the TantStack table state. </p> <p>It should be placed between these buttons: </p> <pre class="brush:php;toolbar:false;"><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></pre></p>
P粉909476457P粉909476457511 days ago631

reply all(1)I'll reply

  • P粉187160883

    P粉1871608832023-09-03 09:31:11

    You need to store the page index in a state variable and pass the setState method to the 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)
      }));

    reply
    0
  • Cancelreply