Pagination
Animated React pagination for shadcn/ui and Tailwind CSS: the drop-in Pagination adds a clear current page, asChild links and focus-safe disabled states — plus a Motion block whose active indicator glides between pages, whose numbers roll as the range shifts, and whose smart ellipsis keeps the bar a constant width.
- Drop-in shadcn API
- Motion layoutId
- Smart ellipsis range
- aria-current
- prefers-reduced-motion
Showing 1–10 of 240 results
"use client";
import * as React from "react";
import { AnimatedPagination } from "@/components/dusk/pagination/animated-pagination";
const perPage = 10;
const totalItems = 240;
export default function AnimatedPaginationDemo() {
const [page, setPage] = React.useState(1);
const totalPages = Math.ceil(totalItems / perPage);
const from = (page - 1) * perPage + 1;
const to = Math.min(page * perPage, totalItems);
return (
<div className="flex w-full flex-col items-center gap-4">
<AnimatedPagination totalPages={totalPages} page={page} onPageChange={setPage} />
<p className="text-sm text-muted-foreground tabular-nums" aria-live="polite">
Showing <span className="text-foreground">{from}–{to}</span> of {totalItems} results
</p>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/pagination.json1. Install the dependencies.
npm install @radix-ui/react-slot lucide-react2. Copy the source into
components/ui/pagination.tsx.pagination.tsx "use client"; import * as React from "react"; import { Slot } from "@radix-ui/react-slot"; import { ChevronLeftIcon, ChevronRightIcon, MoreHorizontalIcon } from "lucide-react"; import { buttonVariants, type ButtonProps } from "@/components/ui/button"; import { cn } from "@/lib/utils"; /** * DuskUI Pagination — a drop-in upgrade of the shadcn/ui Pagination. * * Same parts, props and data-slot attributes as shadcn (Pagination, * PaginationContent, PaginationItem, PaginationLink, PaginationPrevious, * PaginationNext, PaginationEllipsis) plus: * - `asChild` on PaginationLink (and Previous / Next) to render your router's * Link or a `<button>`. * - The current page gets a neutral outlined surface. * - `aria-disabled` links are dimmed and unclickable but stay focusable. * - The ellipsis is announced as "More pages" instead of being hidden. * CSS only (no Motion). Respects reduced motion. */ function Pagination({ className, ...props }: React.ComponentProps<"nav">) { return ( <nav aria-label="pagination" data-slot="pagination" className={cn("mx-auto flex w-full justify-center", className)} {...props} /> ); } function PaginationContent({ className, ...props }: React.ComponentProps<"ul">) { return ( <ul data-slot="pagination-content" className={cn("flex flex-row items-center gap-0.5 sm:gap-1", className)} {...props} /> ); } function PaginationItem({ ...props }: React.ComponentProps<"li">) { return <li data-slot="pagination-item" {...props} />; } type PaginationLinkProps = { /** Marks the current page: sets aria-current="page" and the active style. */ isActive?: boolean; /** Render the child element (e.g. Next.js `Link` or a `<button>`) instead of an `<a>`. */ asChild?: boolean; } & Pick<ButtonProps, "size"> & React.ComponentProps<"a">; function PaginationLink({ className, isActive, size = "icon", asChild = false, ...props }: PaginationLinkProps) { const Comp = asChild ? Slot : "a"; return ( <Comp aria-current={isActive ? "page" : undefined} data-slot="pagination-link" data-active={isActive} className={cn( buttonVariants({ variant: "ghost", size }), "tabular-nums text-muted-foreground hover:text-foreground", "border border-transparent", "data-[active=true]:border-border data-[active=true]:bg-accent/50 data-[active=true]:text-foreground data-[active=true]:hover:bg-accent", "aria-disabled:pointer-events-none aria-disabled:opacity-50", // Slightly smaller page buttons on phones so a full row fits in ~290px. size === "icon" && "max-sm:size-8", className )} {...props} /> ); } /** Fills an empty `asChild` child (e.g. `<button />`) with the default content. */ function withDefaultContent(asChild: boolean | undefined, children: React.ReactNode, fallback: React.ReactNode) { if (children == null) return fallback; if ( asChild && React.isValidElement<{ children?: React.ReactNode }>(children) && children.props.children == null ) { return React.cloneElement(children, undefined, fallback); } return children; } function PaginationPrevious({ className, children, asChild, ...props }: React.ComponentProps<typeof PaginationLink>) { return ( <PaginationLink aria-label="Go to previous page" size="default" asChild={asChild} className={cn("group/pagination gap-1 px-2 sm:pl-2.5", className)} {...props} > {withDefaultContent( asChild, children, <> <ChevronLeftIcon /> <span className="hidden sm:block">Previous</span> </> )} </PaginationLink> ); } function PaginationNext({ className, children, asChild, ...props }: React.ComponentProps<typeof PaginationLink>) { return ( <PaginationLink aria-label="Go to next page" size="default" asChild={asChild} className={cn("group/pagination gap-1 px-2 sm:pr-2.5", className)} {...props} > {withDefaultContent( asChild, children, <> <span className="hidden sm:block">Next</span> <ChevronRightIcon /> </> )} </PaginationLink> ); } function PaginationEllipsis({ className, ...props }: React.ComponentProps<"span">) { return ( <span data-slot="pagination-ellipsis" className={cn("flex size-8 items-center justify-center text-muted-foreground sm:size-9", className)} {...props} > <MoreHorizontalIcon className="size-4" aria-hidden /> <span className="sr-only">More pages</span> </span> ); } export { Pagination, PaginationContent, PaginationLink, PaginationItem, PaginationPrevious, PaginationNext, PaginationEllipsis, type PaginationLinkProps, };
Replaces components/ui/pagination.tsx with the same parts and data-slot attributes. It styles links with buttonVariants from the DuskUI Button, which the registry installs for you.
Usage
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination"
export function ResultsPagination() {
return (
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious href="?page=1" />
</PaginationItem>
<PaginationItem>
<PaginationLink href="?page=1">1</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationLink href="?page=2" isActive>2</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationEllipsis />
</PaginationItem>
<PaginationItem>
<PaginationNext href="?page=3" />
</PaginationItem>
</PaginationContent>
</Pagination>
)
}Examples
Default
The shadcn composition with an outlined current page. Here asChild renders buttons for local state, and aria-disabled dims Previous / Next at the ends without stealing keyboard focus.
"use client";
import * as React from "react";
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
const total = 10;
export default function PaginationBasicDemo() {
const [page, setPage] = React.useState(2);
const pages = [1, 2, 3];
return (
<Pagination>
<PaginationContent>
<PaginationItem>
{/* asChild renders a <button>; in an app, pass href (or your router's Link) instead. */}
<PaginationPrevious asChild aria-disabled={page === 1 || undefined}>
<button type="button" onClick={() => page > 1 && setPage(page - 1)} />
</PaginationPrevious>
</PaginationItem>
{pages.map((p) => (
<PaginationItem key={p}>
<PaginationLink asChild isActive={p === page}>
<button type="button" onClick={() => setPage(p)}>
{p}
</button>
</PaginationLink>
</PaginationItem>
))}
<PaginationItem>
<PaginationEllipsis />
</PaginationItem>
<PaginationItem>
<PaginationLink asChild isActive={page === total}>
<button type="button" onClick={() => setPage(total)}>
{total}
</button>
</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationNext asChild aria-disabled={page === total || undefined}>
<button type="button" onClick={() => page < total && setPage(page + 1)} />
</PaginationNext>
</PaginationItem>
</PaginationContent>
</Pagination>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Animated Pagination
Pass totalPages and a controlled page (or defaultPage). The indicator glides to the current page via a shared Motion layoutId, and numbers roll up or down as the window of pages shifts. The range always has the same number of slots, so the bar never changes width. Focus follows the page you pick.
Showing 1–10 of 240 results
"use client";
import * as React from "react";
import { AnimatedPagination } from "@/components/dusk/pagination/animated-pagination";
const perPage = 10;
const totalItems = 240;
export default function AnimatedPaginationDemo() {
const [page, setPage] = React.useState(1);
const totalPages = Math.ceil(totalItems / perPage);
const from = (page - 1) * perPage + 1;
const to = Math.min(page * perPage, totalItems);
return (
<div className="flex w-full flex-col items-center gap-4">
<AnimatedPagination totalPages={totalPages} page={page} onPageChange={setPage} />
<p className="text-sm text-muted-foreground tabular-nums" aria-live="polite">
Showing <span className="text-foreground">{from}–{to}</span> of {totalItems} results
</p>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-pagination.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/pagination/animated-pagination.tsx.animated-pagination.tsx "use client"; import * as React from "react"; import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react"; import { AnimatePresence, LayoutGroup, motion, useReducedMotion, type Transition, type Variants, } from "motion/react"; import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, } from "@/components/ui/pagination"; import { cn } from "@/lib/utils"; type PageItem = number | "start-ellipsis" | "end-ellipsis"; const range = (start: number, end: number) => Array.from({ length: Math.max(0, end - start + 1) }, (_, i) => start + i); /** * The visible page items. When there are more pages than fit, the result always * has the same length (2·boundary + 2·siblings + 3), so the bar never changes * width while you page through. */ export function getPaginationItems( page: number, totalPages: number, siblingCount = 1, boundaryCount = 1 ): PageItem[] { const slots = boundaryCount * 2 + siblingCount * 2 + 3; if (totalPages <= slots) return range(1, totalPages); const startPages = range(1, boundaryCount); const endPages = range(totalPages - boundaryCount + 1, totalPages); const siblingsStart = Math.max( Math.min(page - siblingCount, totalPages - boundaryCount - siblingCount * 2 - 1), boundaryCount + 2 ); const siblingsEnd = Math.min( Math.max(page + siblingCount, boundaryCount + siblingCount * 2 + 2), totalPages - boundaryCount - 1 ); return [ ...startPages, siblingsStart > boundaryCount + 2 ? "start-ellipsis" : boundaryCount + 1, ...range(siblingsStart, siblingsEnd), siblingsEnd < totalPages - boundaryCount - 1 ? "end-ellipsis" : totalPages - boundaryCount, ...endPages, ]; } const indicatorSpring: Transition = { type: "spring", bounce: 0.1, duration: 0.3 }; const rollSpring: Transition = { type: "spring", bounce: 0, duration: 0.25 }; export interface AnimatedPaginationProps extends Omit<React.ComponentProps<"nav">, "onChange" | "children"> { /** Number of pages. */ totalPages: number; /** Controlled current page (1-based). */ page?: number; /** Uncontrolled initial page. */ defaultPage?: number; /** Called with the new page. */ onPageChange?: (page: number) => void; /** Pages shown on each side of the current one. */ siblingCount?: number; /** Pages always shown at the start and end. */ boundaryCount?: number; /** Show the Previous / Next buttons. */ showControls?: boolean; /** Text of the Previous / Next buttons (hidden on small screens). Pass `null` for icon-only. */ labels?: { previous: React.ReactNode; next: React.ReactNode } | null; /** * Render real links: return the URL of a page. Clicks still call `onPageChange`; * call `event.preventDefault()` there or use `linkAs` for client-side routing. */ getPageHref?: (page: number) => string; /** Component used for links when `getPageHref` is set, e.g. Next.js `Link`. */ linkAs?: React.ElementType; } /** * Pagination with an indicator that glides to the current page (a shared * Motion `layoutId`), page numbers that roll up or down as the window of pages * shifts, and a smart ellipsis range that keeps the bar a constant width. * * Built on the DuskUI Pagination primitive: a `nav` landmark with * aria-current="page", and focus follows the page you pick. Renders buttons by * default, or real links with `getPageHref`. */ export function AnimatedPagination({ totalPages, page: pageProp, defaultPage = 1, onPageChange, siblingCount = 1, boundaryCount = 1, showControls = true, labels = { previous: "Previous", next: "Next" }, getPageHref, linkAs, className, ...props }: AnimatedPaginationProps) { const layoutId = React.useId(); const reduceMotion = useReducedMotion(); const navRef = React.useRef<HTMLElement>(null); const refocus = React.useRef(false); const [uncontrolled, setUncontrolled] = React.useState(defaultPage); const total = Math.max(1, Math.floor(totalPages)); const page = Math.min(Math.max(1, pageProp ?? uncontrolled), total); // Direction of travel, so numbers roll the right way. Derived during render // from the previous page (React's "store info from previous renders" pattern). const [prevPage, setPrevPage] = React.useState(page); const [direction, setDirection] = React.useState(0); if (prevPage !== page) { setPrevPage(page); setDirection(Math.sign(page - prevPage)); } const items = getPaginationItems(page, total, siblingCount, boundaryCount); // Focus follows the page you clicked, since the clicked slot may now show another number. React.useEffect(() => { if (!refocus.current) return; refocus.current = false; navRef.current?.querySelector<HTMLElement>('[aria-current="page"]')?.focus(); }, [page]); const go = (next: number, fromNumber = false) => { const clamped = Math.min(Math.max(1, next), total); if (clamped === page) return; refocus.current = fromNumber; if (pageProp === undefined) setUncontrolled(clamped); onPageChange?.(clamped); }; const offset = reduceMotion ? 0 : 14; const roll: Variants = { enter: (dir: number) => ({ y: dir * offset, opacity: 0, filter: "blur(2px)" }), center: { y: 0, opacity: 1, filter: "blur(0px)", transitionEnd: { filter: "none" } }, exit: (dir: number) => ({ y: dir * -offset, opacity: 0, filter: "blur(2px)" }), }; const renderLink = ( target: number, content: React.ReactNode, extra: { isActive?: boolean; disabled?: boolean; fromNumber?: boolean; size?: "icon" | "default"; className?: string; label: string } ) => { const handleClick = (event: React.MouseEvent) => { if (extra.disabled) { event.preventDefault(); return; } go(target, extra.fromNumber); }; const common = { "aria-label": extra.label, "aria-disabled": extra.disabled || undefined, onClick: handleClick, }; const LinkComp = linkAs ?? "a"; return ( <PaginationLink asChild isActive={extra.isActive} size={extra.size} className={extra.className}> {getPageHref && !extra.disabled ? ( <LinkComp href={getPageHref(target)} {...common}> {content} </LinkComp> ) : getPageHref ? ( // A disabled link has no href, so it can't be followed. <a role="link" tabIndex={0} {...common}> {content} </a> ) : ( <button type="button" {...common}> {content} </button> )} </PaginationLink> ); }; return ( <Pagination ref={navRef} className={className} {...props}> <LayoutGroup id={layoutId}> <PaginationContent> {showControls && ( <PaginationItem> {renderLink( page - 1, <> <ChevronLeftIcon className="transition-transform duration-200 group-hover/pagination:-translate-x-0.5 motion-reduce:transition-none" /> {labels && <span className="hidden sm:block">{labels.previous}</span>} </>, { label: "Go to previous page", disabled: page <= 1, size: labels ? "default" : "icon", className: cn("group/pagination", labels && "gap-1 px-2 sm:px-2.5"), } )} </PaginationItem> )} {items.map((item, slot) => { const isActive = item === page; return ( // Keyed by slot, so a slot keeps its place while its number rolls. <PaginationItem key={slot}> {typeof item === "number" ? ( renderLink( item, <> {isActive && ( <motion.span layoutId="pagination-indicator" aria-hidden transition={reduceMotion ? { duration: 0 } : indicatorSpring} className="pointer-events-none absolute inset-0 -z-10 rounded-md border bg-accent" /> )} <span className="relative grid h-full min-w-[3ch] place-items-center overflow-hidden"> <AnimatePresence initial={false} custom={direction}> <motion.span key={item} custom={direction} variants={roll} initial="enter" animate="center" exit="exit" transition={rollSpring} className="col-start-1 row-start-1" > {item} </motion.span> </AnimatePresence> </span> </>, { label: isActive ? `Page ${item}` : `Go to page ${item}`, isActive, fromNumber: true, size: "icon", // The gliding indicator replaces the primitive's static active surface. className: "isolate data-[active=true]:border-transparent data-[active=true]:bg-transparent data-[active=true]:shadow-none data-[active=true]:hover:bg-transparent", } ) ) : ( <PaginationEllipsis /> )} </PaginationItem> ); })} {showControls && ( <PaginationItem> {renderLink( page + 1, <> {labels && <span className="hidden sm:block">{labels.next}</span>} <ChevronRightIcon className="transition-transform duration-200 group-hover/pagination:translate-x-0.5 motion-reduce:transition-none" /> </>, { label: "Go to next page", disabled: page >= total, size: labels ? "default" : "icon", className: cn("group/pagination", labels && "gap-1 px-2 sm:px-2.5"), } )} </PaginationItem> )} </PaginationContent> </LayoutGroup> </Pagination> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| totalPages | number | — | Number of pages. |
| page / onPageChange | number / (page: number) => void | — | Controlled current page (1-based). |
| defaultPage | number | 1 | Uncontrolled initial page. |
| siblingCount | number | 1 | Pages shown on each side of the current one. |
| boundaryCount | number | 1 | Pages always shown at the start and end. |
| showControls | boolean | true | Show the Previous / Next buttons. |
| labels | { previous, next } | null | "Previous" / "Next" | Button text (hidden below sm). null for icon-only. |
| getPageHref | (page: number) => string | — | Render real links instead of buttons (good for SEO). |
| linkAs | ElementType | "a" | Link component used with getPageHref, e.g. Next.js Link. |
Animated Pagination — compact & wide
labels={null} gives icon-only arrows. siblingCount={0} makes a tight bar for mobile; raise siblingCount and boundaryCount for wide layouts. The helper getPaginationItems is exported if you want the range for your own markup.
import { AnimatedPagination } from "@/components/dusk/pagination/animated-pagination";
export default function AnimatedPaginationCompactDemo() {
return (
<div className="flex w-full flex-col items-center gap-6">
<AnimatedPagination totalPages={50} defaultPage={25} siblingCount={0} labels={null} aria-label="Compact pagination" />
{/* Thirteen buttons can't fit a phone, so the wide variant scrolls sideways there. */}
<div className="w-full overflow-x-auto pb-1">
<AnimatedPagination
totalPages={99}
defaultPage={48}
siblingCount={2}
boundaryCount={2}
labels={null}
aria-label="Wide pagination"
className="mx-auto w-max"
/>
</div>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-pagination.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/pagination/animated-pagination.tsx.animated-pagination.tsx "use client"; import * as React from "react"; import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react"; import { AnimatePresence, LayoutGroup, motion, useReducedMotion, type Transition, type Variants, } from "motion/react"; import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, } from "@/components/ui/pagination"; import { cn } from "@/lib/utils"; type PageItem = number | "start-ellipsis" | "end-ellipsis"; const range = (start: number, end: number) => Array.from({ length: Math.max(0, end - start + 1) }, (_, i) => start + i); /** * The visible page items. When there are more pages than fit, the result always * has the same length (2·boundary + 2·siblings + 3), so the bar never changes * width while you page through. */ export function getPaginationItems( page: number, totalPages: number, siblingCount = 1, boundaryCount = 1 ): PageItem[] { const slots = boundaryCount * 2 + siblingCount * 2 + 3; if (totalPages <= slots) return range(1, totalPages); const startPages = range(1, boundaryCount); const endPages = range(totalPages - boundaryCount + 1, totalPages); const siblingsStart = Math.max( Math.min(page - siblingCount, totalPages - boundaryCount - siblingCount * 2 - 1), boundaryCount + 2 ); const siblingsEnd = Math.min( Math.max(page + siblingCount, boundaryCount + siblingCount * 2 + 2), totalPages - boundaryCount - 1 ); return [ ...startPages, siblingsStart > boundaryCount + 2 ? "start-ellipsis" : boundaryCount + 1, ...range(siblingsStart, siblingsEnd), siblingsEnd < totalPages - boundaryCount - 1 ? "end-ellipsis" : totalPages - boundaryCount, ...endPages, ]; } const indicatorSpring: Transition = { type: "spring", bounce: 0.1, duration: 0.3 }; const rollSpring: Transition = { type: "spring", bounce: 0, duration: 0.25 }; export interface AnimatedPaginationProps extends Omit<React.ComponentProps<"nav">, "onChange" | "children"> { /** Number of pages. */ totalPages: number; /** Controlled current page (1-based). */ page?: number; /** Uncontrolled initial page. */ defaultPage?: number; /** Called with the new page. */ onPageChange?: (page: number) => void; /** Pages shown on each side of the current one. */ siblingCount?: number; /** Pages always shown at the start and end. */ boundaryCount?: number; /** Show the Previous / Next buttons. */ showControls?: boolean; /** Text of the Previous / Next buttons (hidden on small screens). Pass `null` for icon-only. */ labels?: { previous: React.ReactNode; next: React.ReactNode } | null; /** * Render real links: return the URL of a page. Clicks still call `onPageChange`; * call `event.preventDefault()` there or use `linkAs` for client-side routing. */ getPageHref?: (page: number) => string; /** Component used for links when `getPageHref` is set, e.g. Next.js `Link`. */ linkAs?: React.ElementType; } /** * Pagination with an indicator that glides to the current page (a shared * Motion `layoutId`), page numbers that roll up or down as the window of pages * shifts, and a smart ellipsis range that keeps the bar a constant width. * * Built on the DuskUI Pagination primitive: a `nav` landmark with * aria-current="page", and focus follows the page you pick. Renders buttons by * default, or real links with `getPageHref`. */ export function AnimatedPagination({ totalPages, page: pageProp, defaultPage = 1, onPageChange, siblingCount = 1, boundaryCount = 1, showControls = true, labels = { previous: "Previous", next: "Next" }, getPageHref, linkAs, className, ...props }: AnimatedPaginationProps) { const layoutId = React.useId(); const reduceMotion = useReducedMotion(); const navRef = React.useRef<HTMLElement>(null); const refocus = React.useRef(false); const [uncontrolled, setUncontrolled] = React.useState(defaultPage); const total = Math.max(1, Math.floor(totalPages)); const page = Math.min(Math.max(1, pageProp ?? uncontrolled), total); // Direction of travel, so numbers roll the right way. Derived during render // from the previous page (React's "store info from previous renders" pattern). const [prevPage, setPrevPage] = React.useState(page); const [direction, setDirection] = React.useState(0); if (prevPage !== page) { setPrevPage(page); setDirection(Math.sign(page - prevPage)); } const items = getPaginationItems(page, total, siblingCount, boundaryCount); // Focus follows the page you clicked, since the clicked slot may now show another number. React.useEffect(() => { if (!refocus.current) return; refocus.current = false; navRef.current?.querySelector<HTMLElement>('[aria-current="page"]')?.focus(); }, [page]); const go = (next: number, fromNumber = false) => { const clamped = Math.min(Math.max(1, next), total); if (clamped === page) return; refocus.current = fromNumber; if (pageProp === undefined) setUncontrolled(clamped); onPageChange?.(clamped); }; const offset = reduceMotion ? 0 : 14; const roll: Variants = { enter: (dir: number) => ({ y: dir * offset, opacity: 0, filter: "blur(2px)" }), center: { y: 0, opacity: 1, filter: "blur(0px)", transitionEnd: { filter: "none" } }, exit: (dir: number) => ({ y: dir * -offset, opacity: 0, filter: "blur(2px)" }), }; const renderLink = ( target: number, content: React.ReactNode, extra: { isActive?: boolean; disabled?: boolean; fromNumber?: boolean; size?: "icon" | "default"; className?: string; label: string } ) => { const handleClick = (event: React.MouseEvent) => { if (extra.disabled) { event.preventDefault(); return; } go(target, extra.fromNumber); }; const common = { "aria-label": extra.label, "aria-disabled": extra.disabled || undefined, onClick: handleClick, }; const LinkComp = linkAs ?? "a"; return ( <PaginationLink asChild isActive={extra.isActive} size={extra.size} className={extra.className}> {getPageHref && !extra.disabled ? ( <LinkComp href={getPageHref(target)} {...common}> {content} </LinkComp> ) : getPageHref ? ( // A disabled link has no href, so it can't be followed. <a role="link" tabIndex={0} {...common}> {content} </a> ) : ( <button type="button" {...common}> {content} </button> )} </PaginationLink> ); }; return ( <Pagination ref={navRef} className={className} {...props}> <LayoutGroup id={layoutId}> <PaginationContent> {showControls && ( <PaginationItem> {renderLink( page - 1, <> <ChevronLeftIcon className="transition-transform duration-200 group-hover/pagination:-translate-x-0.5 motion-reduce:transition-none" /> {labels && <span className="hidden sm:block">{labels.previous}</span>} </>, { label: "Go to previous page", disabled: page <= 1, size: labels ? "default" : "icon", className: cn("group/pagination", labels && "gap-1 px-2 sm:px-2.5"), } )} </PaginationItem> )} {items.map((item, slot) => { const isActive = item === page; return ( // Keyed by slot, so a slot keeps its place while its number rolls. <PaginationItem key={slot}> {typeof item === "number" ? ( renderLink( item, <> {isActive && ( <motion.span layoutId="pagination-indicator" aria-hidden transition={reduceMotion ? { duration: 0 } : indicatorSpring} className="pointer-events-none absolute inset-0 -z-10 rounded-md border bg-accent" /> )} <span className="relative grid h-full min-w-[3ch] place-items-center overflow-hidden"> <AnimatePresence initial={false} custom={direction}> <motion.span key={item} custom={direction} variants={roll} initial="enter" animate="center" exit="exit" transition={rollSpring} className="col-start-1 row-start-1" > {item} </motion.span> </AnimatePresence> </span> </>, { label: isActive ? `Page ${item}` : `Go to page ${item}`, isActive, fromNumber: true, size: "icon", // The gliding indicator replaces the primitive's static active surface. className: "isolate data-[active=true]:border-transparent data-[active=true]:bg-transparent data-[active=true]:shadow-none data-[active=true]:hover:bg-transparent", } ) ) : ( <PaginationEllipsis /> )} </PaginationItem> ); })} {showControls && ( <PaginationItem> {renderLink( page + 1, <> {labels && <span className="hidden sm:block">{labels.next}</span>} <ChevronRightIcon className="transition-transform duration-200 group-hover/pagination:translate-x-0.5 motion-reduce:transition-none" /> </>, { label: "Go to next page", disabled: page >= total, size: labels ? "default" : "icon", className: cn("group/pagination", labels && "gap-1 px-2 sm:px-2.5"), } )} </PaginationItem> )} </PaginationContent> </LayoutGroup> </Pagination> ); }
Animated Pagination — few pages
With few pages every number is shown and the indicator simply glides between them. Rename the controls with labels — e.g. Newer / Older for a blog.
import { AnimatedPagination } from "@/components/dusk/pagination/animated-pagination";
export default function AnimatedPaginationFewDemo() {
return (
<AnimatedPagination
totalPages={5}
defaultPage={1}
labels={{ previous: "Newer", next: "Older" }}
aria-label="Blog pages"
/>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-pagination.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/pagination/animated-pagination.tsx.animated-pagination.tsx "use client"; import * as React from "react"; import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react"; import { AnimatePresence, LayoutGroup, motion, useReducedMotion, type Transition, type Variants, } from "motion/react"; import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, } from "@/components/ui/pagination"; import { cn } from "@/lib/utils"; type PageItem = number | "start-ellipsis" | "end-ellipsis"; const range = (start: number, end: number) => Array.from({ length: Math.max(0, end - start + 1) }, (_, i) => start + i); /** * The visible page items. When there are more pages than fit, the result always * has the same length (2·boundary + 2·siblings + 3), so the bar never changes * width while you page through. */ export function getPaginationItems( page: number, totalPages: number, siblingCount = 1, boundaryCount = 1 ): PageItem[] { const slots = boundaryCount * 2 + siblingCount * 2 + 3; if (totalPages <= slots) return range(1, totalPages); const startPages = range(1, boundaryCount); const endPages = range(totalPages - boundaryCount + 1, totalPages); const siblingsStart = Math.max( Math.min(page - siblingCount, totalPages - boundaryCount - siblingCount * 2 - 1), boundaryCount + 2 ); const siblingsEnd = Math.min( Math.max(page + siblingCount, boundaryCount + siblingCount * 2 + 2), totalPages - boundaryCount - 1 ); return [ ...startPages, siblingsStart > boundaryCount + 2 ? "start-ellipsis" : boundaryCount + 1, ...range(siblingsStart, siblingsEnd), siblingsEnd < totalPages - boundaryCount - 1 ? "end-ellipsis" : totalPages - boundaryCount, ...endPages, ]; } const indicatorSpring: Transition = { type: "spring", bounce: 0.1, duration: 0.3 }; const rollSpring: Transition = { type: "spring", bounce: 0, duration: 0.25 }; export interface AnimatedPaginationProps extends Omit<React.ComponentProps<"nav">, "onChange" | "children"> { /** Number of pages. */ totalPages: number; /** Controlled current page (1-based). */ page?: number; /** Uncontrolled initial page. */ defaultPage?: number; /** Called with the new page. */ onPageChange?: (page: number) => void; /** Pages shown on each side of the current one. */ siblingCount?: number; /** Pages always shown at the start and end. */ boundaryCount?: number; /** Show the Previous / Next buttons. */ showControls?: boolean; /** Text of the Previous / Next buttons (hidden on small screens). Pass `null` for icon-only. */ labels?: { previous: React.ReactNode; next: React.ReactNode } | null; /** * Render real links: return the URL of a page. Clicks still call `onPageChange`; * call `event.preventDefault()` there or use `linkAs` for client-side routing. */ getPageHref?: (page: number) => string; /** Component used for links when `getPageHref` is set, e.g. Next.js `Link`. */ linkAs?: React.ElementType; } /** * Pagination with an indicator that glides to the current page (a shared * Motion `layoutId`), page numbers that roll up or down as the window of pages * shifts, and a smart ellipsis range that keeps the bar a constant width. * * Built on the DuskUI Pagination primitive: a `nav` landmark with * aria-current="page", and focus follows the page you pick. Renders buttons by * default, or real links with `getPageHref`. */ export function AnimatedPagination({ totalPages, page: pageProp, defaultPage = 1, onPageChange, siblingCount = 1, boundaryCount = 1, showControls = true, labels = { previous: "Previous", next: "Next" }, getPageHref, linkAs, className, ...props }: AnimatedPaginationProps) { const layoutId = React.useId(); const reduceMotion = useReducedMotion(); const navRef = React.useRef<HTMLElement>(null); const refocus = React.useRef(false); const [uncontrolled, setUncontrolled] = React.useState(defaultPage); const total = Math.max(1, Math.floor(totalPages)); const page = Math.min(Math.max(1, pageProp ?? uncontrolled), total); // Direction of travel, so numbers roll the right way. Derived during render // from the previous page (React's "store info from previous renders" pattern). const [prevPage, setPrevPage] = React.useState(page); const [direction, setDirection] = React.useState(0); if (prevPage !== page) { setPrevPage(page); setDirection(Math.sign(page - prevPage)); } const items = getPaginationItems(page, total, siblingCount, boundaryCount); // Focus follows the page you clicked, since the clicked slot may now show another number. React.useEffect(() => { if (!refocus.current) return; refocus.current = false; navRef.current?.querySelector<HTMLElement>('[aria-current="page"]')?.focus(); }, [page]); const go = (next: number, fromNumber = false) => { const clamped = Math.min(Math.max(1, next), total); if (clamped === page) return; refocus.current = fromNumber; if (pageProp === undefined) setUncontrolled(clamped); onPageChange?.(clamped); }; const offset = reduceMotion ? 0 : 14; const roll: Variants = { enter: (dir: number) => ({ y: dir * offset, opacity: 0, filter: "blur(2px)" }), center: { y: 0, opacity: 1, filter: "blur(0px)", transitionEnd: { filter: "none" } }, exit: (dir: number) => ({ y: dir * -offset, opacity: 0, filter: "blur(2px)" }), }; const renderLink = ( target: number, content: React.ReactNode, extra: { isActive?: boolean; disabled?: boolean; fromNumber?: boolean; size?: "icon" | "default"; className?: string; label: string } ) => { const handleClick = (event: React.MouseEvent) => { if (extra.disabled) { event.preventDefault(); return; } go(target, extra.fromNumber); }; const common = { "aria-label": extra.label, "aria-disabled": extra.disabled || undefined, onClick: handleClick, }; const LinkComp = linkAs ?? "a"; return ( <PaginationLink asChild isActive={extra.isActive} size={extra.size} className={extra.className}> {getPageHref && !extra.disabled ? ( <LinkComp href={getPageHref(target)} {...common}> {content} </LinkComp> ) : getPageHref ? ( // A disabled link has no href, so it can't be followed. <a role="link" tabIndex={0} {...common}> {content} </a> ) : ( <button type="button" {...common}> {content} </button> )} </PaginationLink> ); }; return ( <Pagination ref={navRef} className={className} {...props}> <LayoutGroup id={layoutId}> <PaginationContent> {showControls && ( <PaginationItem> {renderLink( page - 1, <> <ChevronLeftIcon className="transition-transform duration-200 group-hover/pagination:-translate-x-0.5 motion-reduce:transition-none" /> {labels && <span className="hidden sm:block">{labels.previous}</span>} </>, { label: "Go to previous page", disabled: page <= 1, size: labels ? "default" : "icon", className: cn("group/pagination", labels && "gap-1 px-2 sm:px-2.5"), } )} </PaginationItem> )} {items.map((item, slot) => { const isActive = item === page; return ( // Keyed by slot, so a slot keeps its place while its number rolls. <PaginationItem key={slot}> {typeof item === "number" ? ( renderLink( item, <> {isActive && ( <motion.span layoutId="pagination-indicator" aria-hidden transition={reduceMotion ? { duration: 0 } : indicatorSpring} className="pointer-events-none absolute inset-0 -z-10 rounded-md border bg-accent" /> )} <span className="relative grid h-full min-w-[3ch] place-items-center overflow-hidden"> <AnimatePresence initial={false} custom={direction}> <motion.span key={item} custom={direction} variants={roll} initial="enter" animate="center" exit="exit" transition={rollSpring} className="col-start-1 row-start-1" > {item} </motion.span> </AnimatePresence> </span> </>, { label: isActive ? `Page ${item}` : `Go to page ${item}`, isActive, fromNumber: true, size: "icon", // The gliding indicator replaces the primitive's static active surface. className: "isolate data-[active=true]:border-transparent data-[active=true]:bg-transparent data-[active=true]:shadow-none data-[active=true]:hover:bg-transparent", } ) ) : ( <PaginationEllipsis /> )} </PaginationItem> ); })} {showControls && ( <PaginationItem> {renderLink( page + 1, <> {labels && <span className="hidden sm:block">{labels.next}</span>} <ChevronRightIcon className="transition-transform duration-200 group-hover/pagination:translate-x-0.5 motion-reduce:transition-none" /> </>, { label: "Go to next page", disabled: page >= total, size: labels ? "default" : "icon", className: cn("group/pagination", labels && "gap-1 px-2 sm:px-2.5"), } )} </PaginationItem> )} </PaginationContent> </LayoutGroup> </Pagination> ); }
API Reference
Same parts as shadcn/ui: Pagination (a nav), PaginationContent, PaginationItem, PaginationLink, PaginationPrevious, PaginationNext and PaginationEllipsis. The additions are below.
| Prop | Type | Default | Description |
|---|---|---|---|
| isActive | boolean | false | On PaginationLink: sets aria-current="page" and the active style. |
| asChild | boolean | false | On PaginationLink / Previous / Next: render your Link or a <button>. An empty child gets the default chevron and label. |
| size | Button size | "icon" | On PaginationLink: any DuskUI Button size. |
| aria-disabled | boolean | — | Dims the link and blocks pointer clicks while keeping it focusable. |
Accessibility
- Pagination renders a nav landmark labelled “pagination”; rename it with aria-label when a page has several.
- The current page carries aria-current="page"; the gliding indicator is decorative and aria-hidden.
- Previous / Next use aria-disabled at the ends, so keyboard focus isn't dropped when you reach the first or last page.
- Animated Pagination gives every number an accessible name (“Go to page 7”) and moves focus to the newly selected page, since the slot you clicked may now show another number.
- The ellipsis is announced as “More pages” rather than being silently skipped.
- Under prefers-reduced-motion the indicator jumps and numbers crossfade without sliding.