Setting Up Pagination with TanStack Table
Provides code to set up pagination in a TanStack Table, covering both the setup of page controls and the integration with the table's data.
const { page, canPreviousPage, canNextPage, pageOptions, gotoPage, nextPage, previousPage, setPageSize } = useTable({
// Table options here
// Typically includes columns and data
},
usePagination)
This code snippet initializes pagination functionality using the useTable hook from TanStack Table, alongside usePagination plugin. It destructures methods and properties needed for managing pagination.
<div>
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>{'<<'}</button>
<button onClick={() => previousPage()} disabled={!canPreviousPage}>Previous</button>
<button onClick={() => nextPage()} disabled={!canNextPage}>Next</button>
<button onClick={() => gotoPage(pageOptions.length - 1)} disabled={!canNextPage}>{'>>'}</button>
</div>
This JSX code creates buttons for navigating through the table pages. It includes functionality for moving to the first, previous, next, and last page, with each button appropriately disabled when the corresponding navigation action isn't possible.
<select
value={pageSize}
onChange={e => {
setPageSize(Number(e.target.value))
}}
>
{[10, 20, 30, 40, 50].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
This snippet adds a select dropdown that lets users choose the number of items to display per page. It iterates over an array of page sizes, creating an option for each size. The setPageSize method updates the table's page size based on the user's selection.