usePagination
@volvo-cars/react-headless v0.24.7
Generates a page list with ellipsis for navigating paginated content like search results, tables, or article lists.
import { usePagination } from '@volvo-cars/react-headless';
function Pagination() { const { pages, activePage, setPage, previousButtonProps, nextButtonProps } = usePagination({ totalPages: 20, initialPage: 1 });
return ( <nav aria-label="Pagination"> <button {...previousButtonProps}>Previous</button> {pages.map((item, index) => item.type === 'PAGE' ? ( <button key={index} aria-current={item.page === activePage ? 'page' : undefined} onClick={() => setPage(item.page)} > {item.page} </button> ) : ( <span key={index}>…</span> ), )} <button {...nextButtonProps}>Next</button> </nav> );}Page item types
Section titled “Page item types”The pages array contains objects with a type field:
| Type | Description |
|---|---|
PAGE | A clickable page number |
ELLIPSIS | Gap indicator (always visible) |
ELLIPSIS_SMALL | Gap indicator for small screens (hidden on lg+) |
Pages with isAdditional: true are extra pages shown on larger screens. Hide them on mobile with until-lg:hidden.
Responsive behavior
Section titled “Responsive behavior”The hook generates different page counts based on screen size:
{ pages.map((item, index) => ( <button key={index} className={item.isAdditional ? 'until-lg:hidden' : undefined} > {item.page} </button> ));}Controlled pagination
Section titled “Controlled pagination”For server-side pagination or URL-synced state, use page and onPageChange:
import { useSearchParams } from 'next/navigation';import { usePagination } from '@volvo-cars/react-headless';
function ControlledPagination({ totalPages }: { totalPages: number }) { const searchParams = useSearchParams(); const currentPage = Number(searchParams.get('page')) || 1;
const { pages, previousButtonProps, nextButtonProps } = usePagination({ totalPages, page: currentPage, onPageChange: (page) => { // Update URL or fetch new data }, });
// ...}usePagination accepts an options object:
totalPages– total number of pages (required)initialPage– starting page for uncontrolled usage (default:1)page– controlled current pageonPageChange– callback fired when the page changes
Returns:
pages– array of page items withtype,page, andisAdditionalactivePage– the currently active page (1-indexed)setPage– function to navigate to a specific pagepreviousButtonProps– props to spread on the previous button (onClick,disabled)nextButtonProps– props to spread on the next button (onClick,disabled)