usePagination
The page math behind Pagination, without the bar. The current page, the page count, the items to draw with their ellipses, the item range on the page, and the moves between pages.
usePagination is the state and the arithmetic of a pager, with nothing drawn. Pagination is built on it. Reach for it when you draw a pager of your own, or when a list paged on the client needs the slice to show.
import { usePagination } from '@42-central/ui-react';
const { page, items, range, setPage, next, previous } = usePagination({
count: 95,
pageSize: 10,
});Pages are 1-based throughout, as they're printed.
A pager of your own
items is the bar: each entry is a page ({ type: 'page', value }) or an ellipsis ({ type: 'ellipsis', index }, where index is its position, a stable key). Here it draws plain Buttons.
Chapter 7 of 15
Code
const { items, page, setPage, previous, next, canPrevious, canNext } = usePagination({
pages: 15,
defaultPage: 7,
});
<nav aria-label="Chapters">
<Button disabled={!canPrevious} onClick={previous}>Back</Button>
{items.map((item) =>
item.type === 'ellipsis' ? (
<span key={`e${item.index}`} aria-hidden>⋯</span>
) : (
<Button
key={item.value}
variant={item.value === page ? 'filled' : 'subtle'}
aria-current={item.value === page ? 'page' : undefined}
onClick={() => setPage(item.value)}
>
{item.value}
</Button>
),
)}
<Button disabled={!canNext} onClick={next}>Forward</Button>
</nav>Once there are more pages than slots (2 × siblings + 2 × boundaries + 3), items keeps that length wherever the page is: an ellipsis that would hide a single page is that page instead. The bar keeps its width as you move through it.
Controlled or not
Like a kit component, it takes page and onPageChange to be controlled, or defaultPage to start somewhere. The moves (setPage, next, previous, first, last) clamp to the existing pages and do nothing when they wouldn't change the page, so onPageChange only fires for a real move.
When the total shrinks under the current page (a filter leaves 2 pages while you're on the 5th), the returned page is clamped to the last page. The hook doesn't call onPageChange for that: it can't during render, and your state may be about to change anyway. Reset the page yourself where the filter changes.
The range on the page
With count, range is the first and last item on the page, 1-based and inclusive: { from: 21, to: 30 }. It is both the "21–30 of 95" line and, minus one at the start, the slice of a list paged on the client: rows.slice(range.from - 1, range.to). With pages there is no item count, so range is null.
API
Prop
Type
Returns:
Prop
Type
paginationRange({ page, totalPages, siblings, boundaries }) is exported too: the same item list as plain numbers and "ellipsis", for code outside React.