Primitives
Animated Number Avatar Badge Button Button Group Toggle Toggle Group Checkbox Chip Countdown Divider Fab Grid Icon Image Input Search Input Textarea Label Loader Marquee Masked Input Message Bubble Notification Banner Offline Banner Progress Progress Ring Radio Group Range Slider Rating Separator Skeleton Slider Stack Stepper Switch Text Theme Toggle Ticker Typing IndicatorComposed
Accordion Achievement Badge Action Bar Action Sheet Action Swap Activity Rings Add to Cart Button Address Card Agenda List Alert Amount Keypad Animated Icons App Bar Audio Message Audio Recorder Autocomplete Avatar Group Balance Display Bar List Barcode Before After Biometric Gate Bloom Menu Bottom Sheet Paywall Sheet Side Sheet Breadcrumb Calendar Calendar Strip Card Carousel Cart Item Character Charts Chat Composer Chat List Item Choice Card Circle Reveal Coach Marks Collapsible Collapsible Header Color Picker Combobox Command Palette Comment Thread Confetti Consent Sheet Context Menu Copy Field Country Picker Coupon Input Currency Input Data Table Date Range Picker Day Schedule Dialog Dock Donut Chart Drawer Driver Card Dropdown Menu Drum Picker Emoji Picker Empty State Error State Event Card Expandable Control Fader Feature Gate File Picker Filter Bar Follow Button Form Gauge Glass Glass Cluster Glass Dock Morph Glass Fab Morph Glass Lab Glass Orb Glass Search Morph Glass Sheet Edge Gradient Button Headline New Heatmap Image Cropper Image Viewer Kanban Card Keyboard Avoiding Keyboard Toolbar Leaderboard Level Progress Lightbox Like Button Line Chart List Reorderable List Swipeable Row Location Card Location Search Map Sheet Map View Markdown View Media Controls Media Picker Media Tile Mention Input Meter Bar Mini Player Mood Slider Morphing Modal Multi Select Navigation Rail Notification Item Number Input Onboarding Pager Order Card Order Summary OTP Input Pagination Paper Clip New Parallax Header Pass Card Password Strength Payment Button Payment Card Payment Method Permission Primer Phone Input PIN Pad Polaroid New Poll Popover Post Card Postage Stamp New Price Tag Pricing Table Product Card Product Gallery Profile Header Promo Banner Prompt Input Property Card Pull To Refresh QR Code Quick Actions Quick Replies Rating Summary Reaction Picker Resend Timer Review Card Review Prompt Ride Option Save Button Scan Frame Scroll Spy Tabs Seat Map Section Header Section Index Segmented Control Select Share Button Share Sheet Shutter Button Signature Pad Slide to Confirm Slot Picker Smart Banner Social Login Button Sparkline Splash Screen Split Button Stat Card Stateful Button Status Dot Step Flow Steps Sticker New Stopwatch Stories Progress Stories Viewer Story Ring Streak Counter Streaming Text Success Seal Swipe Deck Tabs Tag Input Tape New Text Reveal Thinking Indicator Time Picker Timeline Timer Ring Tip Selector Toast Toolbar Tooltip Track Row Transaction Row Trip Progress Variant Picker Video Controls Waveform Weather Card Weekday Picker Zoom TransitionScreens
Account Switcher Biometric Setup Delete Account Forgot Password Grow Auth Login Login — Dark Stage Login — Dense Work Login — Editorial Login — Illustrated Login — Minimal Ink Login — Social Login — Video Loop Food Onboarding Onboarding Onboarding Dark Objects Onboarding Editorial Onboarding Illustrated Onboarding Personalize Onboarding Photo Carousel OTP Verification Passkey — Create Password Reset Permission — Notifications Phone Verification Onboarding Quiz Session Devices Signup Sign-up Chat Sign-up Photo Sheet Social Auth Split Auth Verify Identity Welcome AI Chat AI Assistant Channels List Chat Info Chat List Chat Media Chat Thread Create Group Group Info Message Requests New Message Kept Messages Accessibility Activity Log Appearance Authenticator Blocked Accounts Export Your Data Downloads Edit Profile Edit Profile — Rows Emergency Call Empty States Set Error State Send Feedback Device Locator Help Center Home — Bento Home — Dark Home — Editorial Home Feed Invite Friends Language & Region Linked Accounts Not Found (404) Notification Settings Notifications Password Vault Paywall Paywall — Comparison Paywall — Dark Stage Paywall — Editorial Paywall — Photo Paywall — Trial Timeline Privacy Profile Profile — Gamified Profile — Minimal Profile — Photo Hero QR Scanner Report Issue Saved Items Phone Time Search Search — Command Palette Search — Visual Account Health Settings Settings — Dark Device Settings — Search Storage & Data Terms & Privacy Dating Chat Dating Filters Profile Discover Its A Match Into You Matches Profile Detail Profile Editor Courier Matching Delivery History Delivery Support Package Schedule Parcel Tracking Proof Of Delivery Quick Aisle Quick Home Send Package Substitutions Add Payment Address Book Cart Categories Checkout Checkout — Steps Checkout Success Delivery Filters & Sort Flash Sale Gift Cards Loyalty Points Order Cancel Order Detail Orders Pay Later Checkout Payment Methods Product Detail Product Detail — Hero Product Grid Product Reviews Promo Codes Recently Viewed Return Items Search Results Shop Assistant Store Home Tip & Rate Courier Order Tracking Wishlist Write a Review Event Checkin Event Hero Events Discover My Tickets Seat Selection Ticket Checkout Add Card Bank Accounts Dashboard — Bento Bill Pay Budgets Card Details Crypto Portfolio Finance Dashboard Dashboard — Dark Exchange Currency Expense List Invoice Detail Manage Cards Plan Management Savings Goals Send Money Spending Analytics Split Bill Subscriptions Token Detail Token Swap Transactions Wallet Home Wallet Movers Courier Tracking Food Cart Food Home Food Orders Grocery List Recipe Detail Restaurant — Dark Restaurant Detail Activity Rings Fitness Home Habit Quest Habit Tracker Meal Planner Med Store Meditation Player Mood Check-in Nutrition Home Period Tracker Prior Auth Prior Auth Cases Quest Complete Run Tracking Rx Scan Sleep Tracker Telehealth Booking Walk Map Water Tracker Workout Complete Workout Detail Workout Session Applications Apply Company Interview Schedule Job Detail Job Feed Resume Saved Jobs Create Listing Item Chat Listing Detail Make Offer Market Checkout Market Home Market Search My Listings Offers Inbox Seller Profile Audiobook Player Camera Gallery Albums Game Store Mini Player Music Player Photo Editor Photo Gallery Playlist Detail Podcast Player Clips Feed Serene Home Sound Mixer Stories Video Call Video Player Article Reader Course Detail Event Detail Memory Onboarding Icon Lab Leaderboard Lesson Player Match Detail News Editorial News Home Plant Care Prediction Live Prediction Welcome Smart Home Standings Ticket Wallet Topics Follow Weather Detail Add Task Sheet Alarm Clock Calendar Day Calendar Month Doc Scanner File Manager Focus Timer Journal Kanban Board Mail Inbox Mail Thread Note Editor Notes List Reminders Task List Time Blocks Agent Profile Compare Homes Mortgage Calculator Property Detail Rental Application Saved Homes Schedule Tour Search List Search Map Complete Destination Driver Arriving Ev Charging History Home In Trip Matching Options Parking Receipt Safety Schedule Scooter Unlock Booking Confirmed Booking Review Booking Slots My Bookings Pro On The Way Provider Detail Provider List Rate Service Services Home Arc Create Arc Detail Arc Onboarding Avatar Creator Comments Sheet Create Post Explore Grid Followers List Hashtag Feed Mentions Post Detail Post Hero Social Profile Boarding Pass Booking Confirm Car Rental Trip Discover Flight Live Flight Preferences Flight Results Flight Search Hotel Detail Live Transit Trip — Map Day Trip — Rideshare Request Seat Select Travel Home Trip Itinerary Trip OnboardingNothing matches — try another word.
Pagination
Pagination in three forms: numbered pages, page dots that stretch as you swipe, and a Show more button that shows loading dots and marks the end of the list.
Preview
import * as React from "react";
import { forwardRef } from "react";
import { Pressable, View, type GestureResponderEvent, type ViewProps } from "react-native";
import Animated, {
cancelAnimation,
Easing,
interpolate,
Extrapolation,
useAnimatedStyle,
useSharedValue,
withDelay,
withRepeat,
withSpring,
withTiming,
type SharedValue,
} from "react-native-reanimated";
import { AnimatedPressable, cn, ease, spring, tempo, timing, useHaptic, usePressAnimation, useReducedMotion, useTheme } from "@lumioui/core";
import { Icon } from "../icon/icon";
import { Text } from "../text/text";
/**
* Pagination — the three ways a real app pages content:
* <Pagination total={12} page={page} onPageChange={setPage} /> numbered pager
* <PageDots count={5} progress={scrollProgress} /> scroll-coupled page dots
* <LoadMore onLoadMore={fetchNext} hasMore remaining={24} /> "Show more" / infinite footer
* Also available as Pagination.Dots and Pagination.LoadMore.
*
* Pagination is chrome, so its light stays quiet: the current page's disc
* switches on where it is (no sliding through other numbers), the dots are
* lamps whose brightness follows the finger, and a loading footer swaps its
* label in place for three dots that brighten in turn.
* Expo Go compatible.
*/
const clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi);
const IGNITE = { duration: timing.fast.duration, easing: Easing.bezier(...ease.out) } as const;
const DIM = { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) } as const;
/* ------------------------------------------------------------------ */
/* Numbered pager */
/* ------------------------------------------------------------------ */
type PageToken = number | "start-ellipsis" | "end-ellipsis";
/** Page list with ellipses — always `boundaries` pages at each edge and
* `siblings` pages either side of the current one, so the row width stays
* constant while you page (no jumping arrows). */
function buildPages(page: number, total: number, siblings: number, boundaries: number): PageToken[] {
const slots = boundaries * 2 + siblings * 2 + 3;
if (total <= slots) return Array.from({ length: total }, (_, i) => i + 1);
const left = Math.max(page - siblings, boundaries + 2);
const right = Math.min(page + siblings, total - boundaries - 1);
const showStartGap = left > boundaries + 2;
const showEndGap = right < total - boundaries - 1;
const out: PageToken[] = [];
for (let i = 1; i <= boundaries; i++) out.push(i);
if (!showStartGap) {
for (let i = boundaries + 1; i <= boundaries + 2 + siblings * 2; i++) out.push(i);
out.push("end-ellipsis");
} else if (!showEndGap) {
out.push("start-ellipsis");
for (let i = total - boundaries - 1 - siblings * 2; i <= total - boundaries; i++) out.push(i);
} else {
out.push("start-ellipsis");
for (let i = left; i <= right; i++) out.push(i);
out.push("end-ellipsis");
}
for (let i = total - boundaries + 1; i <= total; i++) out.push(i);
return out;
}
/** 40pt cells (hitSlop to 44) — the pager cell size. */
const CELL = 40;
export interface PaginationProps extends Omit<ViewProps, "className"> {
/** Total number of pages. */
total: number;
/** Controlled current page (1-based). */
page?: number;
/** Uncontrolled initial page (1-based). Default 1. */
defaultPage?: number;
/** Fires with the new page when a number or arrow is tapped. */
onPageChange?: (page: number) => void;
/** Pages shown either side of the current one. Default 1. */
siblings?: number;
/** Pages always shown at each end. Default 1. */
boundaries?: number;
/**
* "numbers" — ‹ 1 … 4 5 6 … 12 › with a current-page disc that switches on in place.
* "compact" — ‹ Page 5 of 12 › for narrow rows and table footers.
*/
variant?: "numbers" | "compact";
/** Hide the previous / next arrows. Default false. */
hideArrows?: boolean;
/** Disable every control. */
disabled?: boolean;
/** Haptic on page change. Default true. */
haptic?: boolean;
className?: string;
}
interface ArrowProps {
dir: "prev" | "next";
disabled: boolean;
onPress: () => void;
}
function Arrow({ dir, disabled, onPress }: ArrowProps) {
const press = usePressAnimation({ pressedScale: 0.9, disabled });
return (
<AnimatedPressable
onPress={onPress}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
disabled={disabled}
hitSlop={4}
style={[{ width: CELL, height: CELL }, press.animatedStyle]}
className="items-center justify-center rounded-full"
accessibilityRole="button"
accessibilityLabel={dir === "prev" ? "Previous page" : "Next page"}
accessibilityState={{ disabled }}
aria-disabled={disabled}
>
<Icon name={dir === "prev" ? "chevron-left" : "chevron-right"} size="md" color="foreground" />
</AnimatedPressable>
);
}
interface PageCellProps {
page: number;
active: boolean;
disabled: boolean;
onPress: (page: number) => void;
}
/** The current page's disc switches on from this scale (radio rule — the
* light doesn't travel between numbers). */
const DISC_FROM = 0.94;
const PageCell = React.memo(function PageCell({ page, active, disabled, onPress }: PageCellProps) {
const press = usePressAnimation({ pressedScale: 0.9, disabled });
const reduceMotion = useReducedMotion();
const lit = useSharedValue(active ? 1 : 0);
const scale = useSharedValue(1);
const first = React.useRef(true);
React.useEffect(() => {
if (first.current) {
first.current = false;
return;
}
lit.value = withTiming(active ? 1 : 0, active ? IGNITE : DIM);
if (!active || reduceMotion) return;
scale.value = DISC_FROM;
scale.value = withSpring(1, spring.swap);
}, [active, reduceMotion, lit, scale]);
const discStyle = useAnimatedStyle(() => ({ opacity: lit.value, transform: [{ scale: scale.value }] }));
// Ink crossfades with the disc rather than flipping before it lights.
const restInk = useAnimatedStyle(() => ({ opacity: 1 - lit.value }));
const litInk = useAnimatedStyle(() => ({ opacity: lit.value }));
return (
<AnimatedPressable
onPress={() => onPress(page)}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
disabled={disabled}
hitSlop={2}
style={[{ width: CELL, height: CELL }, press.animatedStyle]}
className="items-center justify-center rounded-full"
accessibilityRole="button"
accessibilityLabel={`Page ${page}`}
accessibilityState={{ selected: active, disabled }}
aria-current={active ? "page" : undefined}
>
<Animated.View
pointerEvents="none"
style={[{ position: "absolute", top: 0, left: 0, width: CELL, height: CELL }, discStyle]}
className="rounded-full bg-primary"
/>
<Animated.Text style={restInk} className="text-[15px] font-medium tabular-nums text-foreground">
{page}
</Animated.Text>
<Animated.View pointerEvents="none" style={[{ position: "absolute", top: 0, left: 0, width: CELL, height: CELL }, litInk]} className="items-center justify-center">
<Text className="text-[15px] font-semibold tabular-nums text-primary-foreground">{page}</Text>
</Animated.View>
</AnimatedPressable>
);
});
const PaginationRoot = forwardRef<React.ElementRef<typeof View>, PaginationProps>(function Pagination(
{
total,
page: controlledPage,
defaultPage = 1,
onPageChange,
siblings = 1,
boundaries = 1,
variant = "numbers",
hideArrows = false,
disabled = false,
haptic = true,
className,
...props
},
ref
) {
const haptics = useHaptic(haptic);
const [internal, setInternal] = React.useState(defaultPage);
const safeTotal = Math.max(1, total);
// Resolved during render — never mirrored in an effect.
const page = clamp(controlledPage ?? internal, 1, safeTotal);
const go = React.useCallback(
(next: number) => {
const p = clamp(next, 1, safeTotal);
if (p === page || disabled) return;
haptics.selection();
if (controlledPage === undefined) setInternal(p);
onPageChange?.(p);
},
[page, safeTotal, disabled, haptics, controlledPage, onPageChange]
);
const tokens = React.useMemo(() => buildPages(page, safeTotal, siblings, boundaries), [page, safeTotal, siblings, boundaries]);
const arrows = !hideArrows;
return (
<View
ref={ref}
className={cn("flex-row items-center justify-center", disabled && "opacity-50", className)}
accessibilityLabel={`Page ${page} of ${safeTotal}`}
{...props}
>
{arrows ? <Arrow dir="prev" disabled={disabled || page <= 1} onPress={() => go(page - 1)} /> : null}
{variant === "compact" ? (
<View className="min-w-[132px] items-center px-2" accessibilityLiveRegion="polite">
<Text className="text-[15px] font-medium tabular-nums">
Page {page} <Text className="text-[15px] text-muted-foreground">of {safeTotal}</Text>
</Text>
</View>
) : (
<View className="flex-row items-center">
{tokens.map((t) =>
typeof t === "number" ? (
<PageCell key={t} page={t} active={t === page} disabled={disabled} onPress={go} />
) : (
<View key={t} style={{ width: CELL - 8, height: CELL }} className="items-center justify-center" accessible={false}>
<Text className="text-[15px] text-muted-foreground">…</Text>
</View>
)
)}
</View>
)}
{arrows ? <Arrow dir="next" disabled={disabled || page >= safeTotal} onPress={() => go(page + 1)} /> : null}
</View>
);
});
PaginationRoot.displayName = "Pagination";
/* ------------------------------------------------------------------ */
/* Page dots */
/* ------------------------------------------------------------------ */
const DOT = 7;
const PILL = 22;
const DOT_GAP = 8;
/** How far the active dot stretches into a pill. */
const STRETCH = PILL - DOT;
/** Dots are lamps: brightness is the readout. Off lamps sit here. */
const LAMP_OFF = 0.25;
export interface PageDotsProps extends Omit<ViewProps, "className"> {
/** Number of pages. */
count: number;
/** Current page (0-based). Used when `progress` isn't supplied. */
index?: number;
/**
* Continuous page position (0 … count-1) on the UI thread — e.g. scrollX /
* pageWidth from useAnimatedScrollHandler. The dots morph with the finger
* instead of snapping when the page settles.
*/
progress?: SharedValue<number>;
/** Tap left / right of the active dot to step a page (page-control style). */
onIndexChange?: (index: number) => void;
/** "pill" — active dot stretches into a capsule. "dot" — classic page dots. Default "pill". */
variant?: "pill" | "dot";
/** "default" ink on canvas, "inverse" white for dots over photos/video. */
tone?: "default" | "inverse";
className?: string;
}
interface DotProps {
i: number;
pos: SharedValue<number>;
variant: "pill" | "dot";
color: string;
}
/**
* One lamp. Brightness and stretch follow the finger on the UI thread.
* The pill is built from transforms only — a fixed left cap, a body that
* scales out along X and a right cap that travels with it — so the caps
* stay truly round and nothing re-lays out per frame. Earlier lamps'
* stretch pushes this one right by clamp(i − pos, 0, 1) × STRETCH, which
* keeps the row exactly as wide as the old width-animated one.
*/
function Dot({ i, pos, variant, color }: DotProps) {
const pill = variant === "pill";
const lampStyle = useAnimatedStyle(() => {
// t = 1 on the active page, falling to 0 one page away — value-coupled.
const t = interpolate(Math.abs(pos.value - i), [0, 1], [1, 0], Extrapolation.CLAMP);
const pushed = pill ? Math.min(Math.max(i - pos.value, 0), 1) * STRETCH : 0;
return {
opacity: LAMP_OFF + t * (1 - LAMP_OFF),
transform: [{ translateX: pushed }],
};
});
const bodyStyle = useAnimatedStyle(() => ({
transform: [{ scaleX: interpolate(Math.abs(pos.value - i), [0, 1], [1, 0], Extrapolation.CLAMP) }],
}));
const capStyle = useAnimatedStyle(() => ({
transform: [{ translateX: interpolate(Math.abs(pos.value - i), [0, 1], [1, 0], Extrapolation.CLAMP) * STRETCH }],
}));
const cap = { position: "absolute", top: 0, left: 0, width: DOT, height: DOT, borderRadius: DOT / 2, backgroundColor: color } as const;
return (
// Offscreen compositing so the overlapping cap/body share one opacity.
<Animated.View needsOffscreenAlphaCompositing style={[{ width: DOT, height: DOT }, lampStyle]}>
<View style={cap} />
{pill ? (
<>
<Animated.View
style={[{ position: "absolute", top: 0, left: DOT / 2, width: STRETCH, height: DOT, backgroundColor: color, transformOrigin: "0% 50%" }, bodyStyle]}
/>
<Animated.View style={[cap, capStyle]} />
</>
) : null}
</Animated.View>
);
}
export const PageDots = forwardRef<React.ElementRef<typeof View>, PageDotsProps>(function PageDots(
{ count, index = 0, progress, onIndexChange, variant = "pill", tone = "default", className, ...props },
ref
) {
const { colors } = useTheme();
const reduceMotion = useReducedMotion();
const haptics = useHaptic();
const local = useSharedValue(index);
React.useEffect(() => {
if (progress) return;
local.value = reduceMotion ? index : withSpring(index, spring.layout);
}, [index, progress, local, reduceMotion]);
const pos = progress ?? local;
const color = tone === "inverse" ? "#FFFFFF" : colors.foreground;
const width = useSharedValue(0);
const step = (delta: number) => {
const next = clamp(index + delta, 0, count - 1);
if (next === index) return;
haptics.selection();
onIndexChange?.(next);
};
const onPress = (e: GestureResponderEvent) => {
if (!onIndexChange) return;
// Left half steps back, right half steps forward — dots are too small
// to hit one by one.
step(e.nativeEvent.locationX < width.value / 2 ? -1 : 1);
};
return (
<Pressable
ref={ref}
onPress={onPress}
disabled={!onIndexChange}
onLayout={(e) => (width.value = e.nativeEvent.layout.width)}
hitSlop={{ top: 8, bottom: 8 }}
className={cn("h-7 flex-row items-center justify-center self-center px-2", className)}
// The pill's stretch is drawn by transforms — reserve its room once.
style={{ gap: DOT_GAP, paddingRight: variant === "pill" ? 8 + STRETCH : 8 }}
accessibilityRole="adjustable"
accessibilityLabel="Page"
accessibilityValue={{ text: `${index + 1} of ${count}` }}
accessibilityActions={[{ name: "increment" }, { name: "decrement" }]}
onAccessibilityAction={(e) => step(e.nativeEvent.actionName === "decrement" ? -1 : 1)}
{...props}
>
{Array.from({ length: count }, (_, i) => (
<Dot key={i} i={i} pos={pos} variant={variant} color={color} />
))}
</Pressable>
);
});
PageDots.displayName = "PageDots";
/* ------------------------------------------------------------------ */
/* Load more / infinite footer */
/* ------------------------------------------------------------------ */
export interface LoadMoreProps extends Omit<ViewProps, "className"> {
/** Fetch the next page. Return a promise and the footer tracks loading itself. */
onLoadMore?: () => void | Promise<unknown>;
/** Controlled loading state (otherwise derived from the onLoadMore promise). */
loading?: boolean;
/** More results exist. When false the footer settles into its end state. Default true. */
hasMore?: boolean;
/** Items still to load — "Show 24 more" reads better than "Load more". */
remaining?: number;
/** Button label. Default "Show {remaining} more" or "Load more". */
label?: string;
/** End-of-list line. Default "You're all caught up". */
endLabel?: string;
/**
* "button" — a full-width secondary button (feeds, reviews).
* "auto" — busy-dots-only footer for FlatList `onEndReached` infinite lists.
*/
variant?: "button" | "auto";
className?: string;
}
/** Busy swaps the label for three dots that brighten in turn — one cycle. */
const BUSY_CYCLE_MS = tempo.roll * 2;
/** Resting brightness and size of a busy dot. */
const DOT_REST = 0.3;
const DOT_SIZE = 6;
/** One busy dot: brightens as the cycle passes its turn, then rests. Opacity
* only — the dots never travel, and reduced motion holds them half lit. */
function BusyDot({ index, lap, color, still }: { index: number; lap: SharedValue<number>; color: string; still: boolean }) {
const style = useAnimatedStyle(() => {
if (still) return { opacity: 0.6 };
const t = (((lap.value - index / 3) % 1) + 1) % 1;
const peak = t < 0.5 ? Math.sin(t * 2 * Math.PI) : 0;
return { opacity: DOT_REST + (1 - DOT_REST) * Math.max(0, peak) };
});
return <Animated.View style={[{ width: DOT_SIZE, height: DOT_SIZE, borderRadius: DOT_SIZE / 2, backgroundColor: color }, style]} />;
}
export const LoadMore = forwardRef<React.ElementRef<typeof View>, LoadMoreProps>(function LoadMore(
{ onLoadMore, loading: controlledLoading, hasMore = true, remaining, label, endLabel = "You're all caught up", variant = "button", className, ...props },
ref
) {
const haptics = useHaptic();
const { colors } = useTheme();
const reduceMotion = useReducedMotion();
const [pending, setPending] = React.useState(false);
const mounted = React.useRef(true);
React.useEffect(() => () => void (mounted.current = false), []);
const loading = controlledLoading ?? pending;
const press = usePressAnimation({ disabled: loading });
// Busy is not a spinner: the label swaps out in place for three dots that
// brighten in turn until the page lands. The pill never resizes.
const labelOn = useSharedValue(loading ? 0 : 1);
const dotsOn = useSharedValue(loading ? 1 : 0);
const lap = useSharedValue(0);
const busyLoop = loading || variant === "auto";
React.useEffect(() => {
labelOn.value = loading ? withTiming(0, DIM) : withDelay(timing.recede.duration, withTiming(1, IGNITE));
dotsOn.value = loading ? withDelay(timing.recede.duration, withTiming(1, IGNITE)) : withTiming(0, DIM);
}, [loading, labelOn, dotsOn]);
React.useEffect(() => {
if (!busyLoop || reduceMotion) {
cancelAnimation(lap);
return;
}
lap.value = 0;
lap.value = withRepeat(withTiming(1, { duration: BUSY_CYCLE_MS, easing: Easing.linear }), -1, false);
return () => cancelAnimation(lap);
}, [busyLoop, lap, reduceMotion]);
const dotsStyle = useAnimatedStyle(() => ({ opacity: dotsOn.value }));
// End state lands with a small rise when the last page arrives.
const end = useSharedValue(hasMore ? 0 : 1);
React.useEffect(() => {
end.value = withTiming(hasMore ? 0 : 1, hasMore ? DIM : IGNITE);
}, [hasMore, end]);
const labelStyle = useAnimatedStyle(() => ({ opacity: labelOn.value }));
const endStyle = useAnimatedStyle(() => ({
opacity: end.value,
transform: [{ translateY: reduceMotion ? 0 : (1 - end.value) * 6 }],
}));
const run = () => {
if (loading || !hasMore) return;
haptics.light();
const r = onLoadMore?.();
if (r && typeof (r as Promise<unknown>).then === "function" && controlledLoading === undefined) {
setPending(true);
(r as Promise<unknown>).finally(() => mounted.current && setPending(false));
}
};
if (!hasMore) {
return (
<Animated.View
ref={ref}
style={endStyle}
className={cn("h-14 flex-row items-center justify-center gap-2", className)}
accessibilityLiveRegion="polite"
{...props}
>
<Icon name="check-circle" size="sm" color="mutedForeground" />
<Text className="text-sm text-muted-foreground">{endLabel}</Text>
</Animated.View>
);
}
if (variant === "auto") {
return (
<View
ref={ref}
className={cn("h-14 flex-row items-center justify-center", className)}
style={{ gap: DOT_SIZE }}
accessibilityRole="progressbar"
accessibilityLabel="Loading more"
{...props}
>
{[0, 1, 2].map((i) => (
<BusyDot key={i} index={i} lap={lap} color={colors.mutedForeground} still={reduceMotion} />
))}
</View>
);
}
const text = label ?? (remaining != null ? `Show ${remaining} more` : "Load more");
return (
<View ref={ref} className={cn("w-full", className)} {...props}>
<AnimatedPressable
onPress={run}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
disabled={loading}
style={press.animatedStyle}
className="h-12 w-full items-center justify-center overflow-hidden rounded-full bg-secondary"
accessibilityRole="button"
accessibilityLabel={loading ? "Loading" : text}
accessibilityState={{ busy: loading, disabled: loading }}
>
<Animated.View style={labelStyle} className="flex-row items-center gap-2">
<Text className="text-[15px] font-semibold text-secondary-foreground">{text}</Text>
<Icon name="chevron-down" size="sm" color="secondaryForeground" />
</Animated.View>
{/* Busy — three dots in the label's place while the next page loads. */}
<Animated.View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={[{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, flexDirection: "row", alignItems: "center", justifyContent: "center", gap: DOT_SIZE }, dotsStyle]}
>
{[0, 1, 2].map((i) => (
<BusyDot key={i} index={i} lap={lap} color={colors.secondaryForeground} still={reduceMotion} />
))}
</Animated.View>
</AnimatedPressable>
</View>
);
});
LoadMore.displayName = "LoadMore";
export const Pagination = Object.assign(PaginationRoot, { Dots: PageDots, LoadMore }); import { Pagination } from "@/components/ui/pagination/pagination";
export function Example() {
return (
<Pagination />
);
} Installation
Install the dependencies
npx expo install react-native-reanimatedAdd the components it builds on
Copy the source from the Code tab into your project
components/ui/pagination/pagination.tsxcomponents/ui/pagination/index.tsIcons it renders
Update the import paths to match your project setup.
Usage
import { PageDots, LoadMore, Pagination } from "@/components/ui/pagination/pagination"; <Pagination /> Also exported: PageDots, LoadMore.
Examples
Swipe between cards in a banking wallet.
import * as React from "react";
import { View, type LayoutChangeEvent } from "react-native";
import Animated, { useAnimatedScrollHandler, useSharedValue, runOnJS } from "react-native-reanimated";
import { PageDots } from "../pagination";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
interface Card {
name: string;
last4: string;
/** Card art is content colour — the chrome stays neutral. The ink card
* carries a hairline so it keeps its edge on a dark canvas. */
tint: string;
balance: string;
cents: string;
detail: string;
}
const CARDS: Card[] = [
{ name: "Everyday", last4: "4417", tint: "border border-border bg-neutral-900", balance: "$2,316", cents: ".08", detail: "Round-ups on · $41.20 saved this month" },
{ name: "Travel", last4: "9052", tint: "bg-tint-teal", balance: "€684", cents: ".50", detail: "No FX fees · Next trip: Porto, Nov 14" },
{ name: "Virtual", last4: "0311", tint: "bg-tint-pink", balance: "$120", cents: ".00", detail: "Subscriptions only · 4 merchants" },
{ name: "Joint", last4: "7726", tint: "bg-tint-green", balance: "$5,902", cents: ".44", detail: "Shared with Tomás · Rent due Nov 1" },
];
/** PaginationDots — swipe between cards in a banking wallet. The dots are
* lamps: brightness and the pill stretch
* follow the scroll offset on the UI thread, so they stretch and brighten with
* the finger mid-swipe; the balance below swaps only when a page settles.
* Tap either side of the dots to step a card. */
export function PaginationDots() {
const [w, setW] = React.useState(0);
const [index, setIndex] = React.useState(0);
const progress = useSharedValue(0);
const last = useSharedValue(0);
const scrollRef = React.useRef<Animated.ScrollView>(null);
const onScroll = useAnimatedScrollHandler(
(e) => {
if (w <= 0) return;
const p = e.contentOffset.x / w;
progress.value = p;
const r = Math.round(p);
if (r !== last.value) {
last.value = r;
runOnJS(setIndex)(r);
}
},
[w]
);
const card = CARDS[index] ?? CARDS[0]!;
return (
<View className="w-full gap-5">
<View className="flex-row items-center justify-between px-1">
<Text className="text-2xl font-bold tracking-tight">Cards</Text>
<View className="h-9 flex-row items-center gap-1.5 rounded-full bg-card px-3">
<Icon name="plus" size="sm" color="foreground" />
<Text className="text-sm font-medium">Add card</Text>
</View>
</View>
<View onLayout={(e: LayoutChangeEvent) => setW(e.nativeEvent.layout.width)} className="w-full">
<Animated.ScrollView
ref={scrollRef}
horizontal
pagingEnabled
showsHorizontalScrollIndicator={false}
onScroll={onScroll}
scrollEventThrottle={16}
>
{CARDS.map((c) => (
<View key={c.last4} style={{ width: w || 358 }} className="px-1">
<View style={{ aspectRatio: 1.586 }} className={`justify-between rounded-3xl p-5 ${c.tint}`}>
<View className="flex-row items-center justify-between">
<Text className="text-[17px] font-semibold text-white">{c.name}</Text>
<Icon name="wifi" size="sm" color="#FFFFFF" />
</View>
<View className="flex-row items-end justify-between">
<Text className="text-base tracking-widest text-white/80 tabular-nums">•••• {c.last4}</Text>
<Text className="text-sm font-semibold text-white">Debit</Text>
</View>
</View>
</View>
))}
</Animated.ScrollView>
</View>
<PageDots
count={CARDS.length}
index={index}
progress={progress}
onIndexChange={(i) => scrollRef.current?.scrollTo({ x: i * w, animated: true })}
/>
<View className="gap-1 rounded-2xl bg-card p-5" accessibilityLiveRegion="polite">
<Text variant="muted">{card.name} balance</Text>
<View className="flex-row items-baseline">
<Text className="text-4xl font-semibold tracking-tight tabular-nums">{card.balance}</Text>
<Text className="text-xl font-semibold text-muted-foreground tabular-nums">{card.cents}</Text>
</View>
<Text className="text-sm text-muted-foreground">{card.detail}</Text>
</View>
</View>
);
} Reviews under a recipe.
import * as React from "react";
import { View } from "react-native";
import { Accent, SwitchOn, rowDelay } from "@lumioui/core";
import { LoadMore } from "../pagination";
import { Avatar } from "../../avatar/avatar";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
interface Review {
name: string;
img: number;
stars: number;
when: string;
body: string;
}
const ALL: Review[] = [
{ name: "Hana Okafor", img: 47, stars: 5, when: "2d", body: "Browned the butter a little longer and it tasted like toffee. Made it twice this week." },
{ name: "Luca Bianchi", img: 12, stars: 4, when: "4d", body: "Halved the sugar and it still set beautifully. Bake time ran 4 minutes over in my oven." },
{ name: "Tess Morgan", img: 32, stars: 5, when: "1w", body: "The flaky salt on top is not optional. Everyone at work asked for the recipe." },
{ name: "Arjun Mehta", img: 59, stars: 5, when: "1w", body: "Rested the dough overnight like the note says. Chewier middles, crisp edges." },
{ name: "Clara Jensen", img: 25, stars: 3, when: "2w", body: "Good flavour but mine spread a lot. Next time I'll chill the trays first." },
{ name: "Omar Farouk", img: 68, stars: 5, when: "2w", body: "Used dark rye flour for a third of the plain. Nutty and not too sweet." },
{ name: "Bea Lawson", img: 44, stars: 4, when: "3w", body: "Swapped in pecans. Would love a gluten-free version of this one." },
{ name: "Mateo Silva", img: 15, stars: 5, when: "1mo", body: "Fastest cookies I've ever made from scratch. Kids helped weigh everything." },
{ name: "Ines Duarte", img: 9, stars: 5, when: "1mo", body: "Doubled the batch and froze half the dough balls. Bake straight from frozen." },
];
const PAGE = 3;
/** PaginationLoadMore — reviews under a recipe. While the next page loads,
* "Show 6 more" swaps in place for three busy dots; the new
* reviews switch on from dim 40ms apart, and after the last page the
* footer ignites a quiet end line once. Orange for food. */
export function PaginationLoadMore() {
const [shown, setShown] = React.useState(PAGE);
// Rows from here on arrived with the last page and switch on in order.
const [freshFrom, setFreshFrom] = React.useState(0);
const rows = ALL.slice(0, shown);
const remaining = ALL.length - shown;
const loadMore = () =>
new Promise<void>((resolve) =>
setTimeout(() => {
setFreshFrom(shown);
setShown((n) => Math.min(ALL.length, n + PAGE));
resolve();
}, 900)
);
return (
<Accent color="orange" className="w-full">
<View className="w-full gap-4">
<View className="flex-row items-end justify-between px-1">
<View className="gap-1">
<Text className="text-xl font-semibold tracking-tight">Reviews</Text>
<Text variant="muted">Brown butter chocolate chip cookies</Text>
</View>
<View className="flex-row items-center gap-1">
<Icon name="star" size="sm" color="primary" filled />
<Text className="text-base font-semibold tabular-nums">4.7</Text>
<Text className="text-sm text-muted-foreground tabular-nums">({ALL.length})</Text>
</View>
</View>
<View className="overflow-hidden rounded-2xl bg-card">
{rows.map((r, i) => (
<SwitchOn key={r.name} delay={i >= freshFrom ? rowDelay(i - freshFrom) : 0}>
{i > 0 ? <View className="ml-16 h-px bg-border" /> : null}
<View className="flex-row gap-3 px-4 py-4">
<Avatar size="md" source={{ uri: `https://i.pravatar.cc/150?img=${r.img}` }} fallback={r.name[0]} alt={r.name} />
<View className="flex-1 gap-1">
<View className="flex-row items-center justify-between">
<Text className="text-[15px] font-semibold">{r.name}</Text>
<Text className="text-xs text-muted-foreground">{r.when}</Text>
</View>
<View className="flex-row gap-0.5" accessibilityLabel={`${r.stars} out of 5 stars`}>
{Array.from({ length: 5 }, (_, s) => (
<Icon key={s} name="star" size="sm" color={s < r.stars ? "primary" : "border"} filled />
))}
</View>
<Text className="text-[15px] leading-snug text-foreground">{r.body}</Text>
</View>
</View>
</SwitchOn>
))}
</View>
<LoadMore
onLoadMore={loadMore}
hasMore={remaining > 0}
remaining={remaining}
endLabel="That's every review"
/>
</View>
</Accent>
);
} A helpdesk inbox paged five tickets at a time.
import * as React from "react";
import { View } from "react-native";
import { SwitchOn, rowDelay } from "@lumioui/core";
import { Pagination } from "../pagination";
import { Text } from "../../text/text";
const PER_PAGE = 5;
const TOTAL_TICKETS = 58;
const PAGES = Math.ceil(TOTAL_TICKETS / PER_PAGE);
const SUBJECTS = [
"Can't export invoices to CSV",
"Two-factor code never arrives",
"Seat count wrong after downgrade",
"Webhook retries flooding endpoint",
"Calendar sync skipped recurring events",
"SSO login loops back to sign-in",
"Refund for duplicate annual charge",
"Dark mode unreadable in reports",
"Bulk import stalls at 80%",
"API rate limit lower than plan",
"Shared views missing for guests",
"Mobile app crashes on attachments",
];
const PEOPLE = ["Noor Haddad", "Ellis Grant", "Mei Watanabe", "Kofi Asante", "Sanna Lindqvist", "Rafael Ortiz", "Ivy Calloway"];
const STATES = [
{ label: "Open", dot: "bg-tint-teal" },
{ label: "Waiting", dot: "bg-tint-amber" },
{ label: "Solved", dot: "bg-neutral-400" },
] as const;
/** Deterministic fake ticket for a global row index — every page looks real. */
function ticket(n: number) {
const subject = SUBJECTS[(n * 7) % SUBJECTS.length]!;
const who = PEOPLE[(n * 3) % PEOPLE.length]!;
const state = STATES[n % 5 === 0 ? 2 : n % 3 === 0 ? 1 : 0]!;
const id = 4810 - n;
const age = n < 4 ? `${(n + 1) * 12}m` : n < 20 ? `${Math.floor(n / 2)}h` : `${Math.floor(n / 6)}d`;
return { id, subject, who, state, age };
}
/** PaginationNumbers — a helpdesk inbox paged five tickets at a time. The
* current page switches on where it is while the last one dims; the new
* page of tickets switches on from dim, 40ms a row. The ellipses shift so
* the row never changes width. Ink, like the tool's own chrome. */
export function PaginationNumbers() {
const [page, setPage] = React.useState(1);
const start = (page - 1) * PER_PAGE;
const rows = Array.from({ length: Math.min(PER_PAGE, TOTAL_TICKETS - start) }, (_, i) => ticket(start + i));
return (
<View className="w-full">
<View className="w-full gap-4">
<View className="flex-row items-end justify-between px-1">
<View className="gap-1">
<Text className="text-2xl font-bold tracking-tight">Tickets</Text>
<Text variant="muted">Billing & accounts queue</Text>
</View>
<Text className="text-sm text-muted-foreground tabular-nums">
{start + 1}–{start + rows.length} of {TOTAL_TICKETS}
</Text>
</View>
<View key={page} className="overflow-hidden rounded-2xl bg-card">
{rows.map((t, i) => (
<SwitchOn key={t.id} delay={rowDelay(i)}>
{i > 0 ? <View className="ml-4 h-px bg-border" /> : null}
<View className="min-h-[68px] justify-center gap-1 px-4 py-3">
<View className="flex-row items-center gap-2">
<View className={`h-2 w-2 rounded-full ${t.state.dot}`} />
<Text numberOfLines={1} className="flex-1 text-[15px] font-medium">
{t.subject}
</Text>
<Text className="text-xs text-muted-foreground tabular-nums">{t.age}</Text>
</View>
<Text numberOfLines={1} className="pl-4 text-sm text-muted-foreground">
#{t.id} · {t.who} · {t.state.label}
</Text>
</View>
</SwitchOn>
))}
</View>
<Pagination total={PAGES} page={page} onPageChange={setPage} />
</View>
</View>
);
} API reference
Pagination
total* number Total number of pages.
—page number Controlled current page (1-based).
—defaultPage number Uncontrolled initial page (1-based). Default 1.
—onPageChange (page: number) => void Fires with the new page when a number or arrow is tapped.
—siblings number Pages shown either side of the current one. Default 1.
—boundaries number Pages always shown at each end. Default 1.
—variant "numbers" | "compact" "numbers" — ‹ 1 … 4 5 6 … 12 › with a current-page disc that switches on in place. "compact" — ‹ Page 5 of 12 › for narrow rows and table footers.
—hideArrows boolean Hide the previous / next arrows. Default false.
—disabled boolean Disable every control.
—haptic boolean Haptic on page change. Default true.
—className string — PageDots
count* number Number of pages.
—index number Current page (0-based). Used when progress isn't supplied.
0 progress SharedValue<number> Continuous page position (0 … count-1) on the UI thread — e.g. scrollX / pageWidth from useAnimatedScrollHandler. The dots morph with the finger instead of snapping when the page settles.
—onIndexChange (index: number) => void Tap left / right of the active dot to step a page (page-control style).
—variant "pill" | "dot" "pill" — active dot stretches into a capsule. "dot" — classic page dots. Default "pill".
"pill" tone "default" | "inverse" "default" ink on canvas, "inverse" white for dots over photos/video.
"default" className string — LoadMore
onLoadMore () => void | Promise<unknown> Fetch the next page. Return a promise and the footer tracks loading itself.
—loading boolean Controlled loading state (otherwise derived from the onLoadMore promise).
—hasMore boolean More results exist. When false the footer settles into its end state. Default true.
true remaining number Items still to load — "Show 24 more" reads better than "Load more".
—label string Button label. Default "Show {remaining} more" or "Load more".
—endLabel string End-of-list line. Default "You're all caught up".
"You're all caught up" variant "button" | "auto" "button" — a full-width secondary button (feeds, reviews). "auto" — busy-dots-only footer for FlatList onEndReached infinite lists.
"button" className string —