Skip to content

usePagination

Edit on GitHub
@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>
);
}

The pages array contains objects with a type field:

TypeDescription
PAGEA clickable page number
ELLIPSISGap indicator (always visible)
ELLIPSIS_SMALLGap 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.

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>
));
}

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 page
  • onPageChange – callback fired when the page changes

Returns:

  • pages – array of page items with type, page, and isAdditional
  • activePage – the currently active page (1-indexed)
  • setPage – function to navigate to a specific page
  • previousButtonProps – props to spread on the previous button (onClick, disabled)
  • nextButtonProps – props to spread on the next button (onClick, disabled)