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.
Image
Image with a placeholder while it loads, a fallback when it fails, and aspect-ratio handling so your layout doesn’t jump when the picture arrives.
Preview
import * as React from "react";
import { forwardRef, useCallback, useEffect, useRef, useState } from "react";
import {
View,
Image as RNImage,
type ImageErrorEventData,
type ImageLoadEventData,
type ImageProps as RNImageProps,
type NativeSyntheticEvent,
} from "react-native";
import Animated, { useSharedValue, useAnimatedStyle, withTiming, runOnJS, Easing } from "react-native-reanimated";
import { cn, createVariant, ease, timing, useReducedMotion } from "@lumioui/core";
/** Image switch-on (DESIGN-TASTE §0b, §5c rule 6): the frame waits as a steady
* dim tile; the photo arrives dim and brightens into place. */
const ARRIVE = { ...timing.normal, easing: Easing.bezier(...ease.out) };
/** The brightening runs a beat longer than the arrival so the photo is seen switching on. */
const BRIGHTEN = { ...timing.slow, easing: Easing.bezier(...ease.out) };
/** How dim the photo is when it first appears. */
const DIM = 0.4;
/**
* Image — RN Image wrapper with rounded variants, aspectRatio,
* a still, dim frame while loading (nothing moves across it, however slow
* the load), a switch-on arrival, and an error fallback slot.
* <Image source={{ uri }} rounded="lg" aspectRatio={16/9} fallback={<Text>!</Text>} />
*/
const imageVariants = createVariant({
base: "overflow-hidden bg-muted",
variants: {
rounded: {
none: "rounded-none",
sm: "rounded-sm",
md: "rounded-md",
lg: "rounded-lg",
xl: "rounded-xl",
// Media tiles and cards (DESIGN-TASTE §3: tiles/media 16–20).
"2xl": "rounded-2xl",
"3xl": "rounded-3xl",
full: "rounded-full",
},
},
defaultVariants: { rounded: "md" },
});
export interface ImageProps extends Omit<RNImageProps, "style" | "className" | "children"> {
/** Corner radius preset. */
rounded?: "none" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "full";
/** width / height ratio applied via style. */
aspectRatio?: number;
/** Slot rendered when the image fails to load. */
fallback?: React.ReactNode;
/** Hide the loading placeholder. Default false. */
hidePlaceholder?: boolean;
/**
* Alt text for the image — alias for `accessibilityLabel`. When neither is
* provided the label is left unset so the OS can decide what to announce.
*/
alt?: string;
className?: string;
style?: RNImageProps["style"];
}
export const Image = forwardRef<React.ElementRef<typeof RNImage>, ImageProps>(
function Image(
{
rounded = "md",
aspectRatio,
fallback,
hidePlaceholder = false,
alt,
accessibilityLabel,
className,
style,
onLoad,
onError,
...props
},
ref
) {
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
// Drop the animated style entirely once the reveal settles — a lingering
// `transform: scale(1)` keeps the element composited on web, which paints
// it above absolutely-positioned siblings (floating chrome).
const [revealed, setRevealed] = useState(false);
// Placeholder stays mounted through its fade-out — hiding it on the same
// frame the image loads would hard-cut the crossfade.
const [showPlaceholder, setShowPlaceholder] = useState(!hidePlaceholder);
const reduce = useReducedMotion();
// frame: 1 while waiting, fades out under the arriving photo.
const frame = useSharedValue(1);
// arrive: photo opacity; lit: how far it has brightened.
const arrive = useSharedValue(0);
const lit = useSharedValue(0);
useEffect(() => {
if (!loading || failed || hidePlaceholder) return;
setShowPlaceholder(true);
}, [loading, failed, hidePlaceholder]);
const placeholderStyle = useAnimatedStyle(() => ({ opacity: frame.value }));
const imageStyle = useAnimatedStyle(() => ({ opacity: arrive.value }));
const veilStyle = useAnimatedStyle(() => ({ opacity: (1 - lit.value) * DIM }));
// Load handlers must keep one identity across renders: on the web the
// image restarts its request whenever onLoad/onError change, so a parent
// that re-renders often (a ticking player, a live clock) would abort the
// load every tick and the photo would never arrive. Latest values ride refs.
const latest = useRef({ onLoad, onError, reduce });
latest.current = { onLoad, onError, reduce };
const switchOn = (instant: boolean) => {
if (instant) {
arrive.value = withTiming(1, timing.fast);
lit.value = 1;
frame.value = 0;
setShowPlaceholder(false);
setRevealed(true);
return;
}
arrive.value = withTiming(1, ARRIVE);
frame.value = withTiming(0, ARRIVE, (finished) => {
if (finished) runOnJS(setShowPlaceholder)(false);
});
lit.value = withTiming(1, BRIGHTEN, (finished) => {
if (finished) runOnJS(setRevealed)(true);
});
};
const handleLoad = useCallback(
(e: NativeSyntheticEvent<ImageLoadEventData>) => {
switchOn(latest.current.reduce);
setLoading(false);
latest.current.onLoad?.(e);
},
// switchOn only touches shared values and state setters, which are stable.
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
const handleError = useCallback(
(e: NativeSyntheticEvent<ImageErrorEventData>) => {
arrive.value = 1;
lit.value = 1;
setRevealed(true);
setLoading(false);
setFailed(true);
latest.current.onError?.(e);
},
[arrive, lit]
);
return (
<View
className={cn(imageVariants({ rounded }), "w-full", className)}
style={aspectRatio != null ? { aspectRatio } : undefined}
accessibilityRole="image"
// No generic "Image" fallback — an absent label lets the OS decide.
accessibilityLabel={alt ?? accessibilityLabel}
>
{!failed ? (
<Animated.Image
ref={ref}
className="h-full w-full"
style={[style, revealed ? undefined : imageStyle]}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
onLoad={handleLoad}
onError={handleError}
{...props}
/>
) : (
<View className="h-full w-full items-center justify-center bg-muted">
{fallback ?? null}
</View>
)}
{/* Dim at first, the photo brightens as this veil lifts. */}
{!failed && !revealed ? (
<Animated.View pointerEvents="none" style={veilStyle} className="absolute inset-0 bg-black" accessibilityElementsHidden importantForAccessibility="no" />
) : null}
{showPlaceholder && !failed && (
<Animated.View
pointerEvents="none"
style={placeholderStyle}
className="absolute inset-0 bg-muted"
accessibilityElementsHidden
importantForAccessibility="no"
/>
)}
</View>
);
}
);
Image.displayName = "Image";
export { imageVariants }; import { Image } from "@/components/ui/image/image";
export function Example() {
return (
<Image />
);
} Installation
Install the dependencies
npx expo install react-native-reanimatedCopy the source from the Code tab into your project
components/ui/image/image.tsxcomponents/ui/image/index.tsUpdate the import paths to match your project setup.
Usage
import { Image } from "@/components/ui/image/image"; <Image /> Examples
A photo in a group chat that didn't download.
import * as React from "react";
import { View } from "react-native";
import { Image } from "../image";
import { Avatar } from "../../avatar/avatar";
import { Button } from "../../button/button";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const BROKEN = "https://invalid.example.invalid/IMG_2291.jpg";
const PHOTO =
"https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=800&h=1000&fit=crop&q=70&auto=format";
/** ImageFallback — a photo in a group chat that didn't download. The
* fallback slot keeps the bubble's shape and offers a retry; tap it and
* the photo loads in place. */
export function ImageFallback() {
const [attempt, setAttempt] = React.useState(0);
const uri = attempt === 0 ? BROKEN : PHOTO;
return (
<View className="w-full gap-3 rounded-3xl bg-card p-4">
<View className="flex-row items-end gap-2">
<Avatar size="sm" source={{ uri: "https://i.pravatar.cc/150?img=45" }} fallback="CA" alt="Clara Ainsworth" />
<View className="flex-1 gap-1">
<Text className="pl-3 text-xs text-muted-foreground">Clara · Beach weekend</Text>
<View className="w-4/5">
<Image
key={attempt}
source={{ uri }}
aspectRatio={4 / 5}
rounded="2xl"
accessibilityLabel="Turquoise water on a quiet beach"
fallback={
<View className="items-center gap-3 px-6">
<Icon name="image" size="lg" color="mutedForeground" />
<Text variant="muted" className="text-center">Photo didn't download</Text>
<Button
size="sm"
variant="secondary"
onPress={() => setAttempt((a) => a + 1)}
icon={<Icon name="refresh" size="sm" color="foreground" />}
>
Try again
</Button>
</View>
}
/>
</View>
</View>
</View>
<View className="max-w-[80%] self-start rounded-2xl bg-secondary px-4 py-2 ml-10">
<Text className="text-[15px]">Found the cove from the map. Bring snorkels!</Text>
</View>
</View>
);
} The hero photo of a trail in a hiking app.
import * as React from "react";
import { Pressable, View } from "react-native";
import { useHaptic } from "@lumioui/core";
import { Image } from "../image";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const PHOTO =
"https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=1000&fit=crop&q=70&auto=format";
/** ImagePhoto — the hero photo of a trail in a hiking app. It fades in
* over its placeholder; tap the heart to save the route. */
export function ImagePhoto() {
const haptics = useHaptic();
const [saved, setSaved] = React.useState(false);
return (
<View className="w-full gap-3">
<View>
<Image
source={{ uri: PHOTO }}
aspectRatio={4 / 5}
rounded="3xl"
accessibilityLabel="Peaks rising above a sea of clouds"
/>
<Pressable
onPress={() => {
haptics.selection();
setSaved((s) => !s);
}}
className="absolute right-3 top-3 h-11 w-11 items-center justify-center rounded-full bg-card"
accessibilityRole="button"
accessibilityLabel={saved ? "Remove from saved" : "Save route"}
accessibilityState={{ selected: saved }}
>
<Icon name="heart" size="md" color={saved ? "destructive" : "foreground"} filled={saved} />
</Pressable>
</View>
<View className="gap-1 px-1">
<View className="flex-row items-center justify-between">
<Text className="text-xl font-semibold tracking-tight">Sentinel Ridge Loop</Text>
<View className="flex-row items-center gap-1">
<Icon name="star" size="sm" color="foreground" filled />
<Text className="text-[15px] font-medium tabular-nums">4.8</Text>
</View>
</View>
<Text variant="muted">11.2 km · 940 m gain · Hard · Est. 5h 10m</Text>
</View>
</View>
);
} A music app's "Pick up again" row, where each radius says what you're looking at.
import * as React from "react";
import { Pressable, View } from "react-native";
import { Accent, useHaptic } from "@lumioui/core";
import { Image, type ImageProps } from "../image";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const img = (id: string) => `https://images.unsplash.com/${id}?w=300&h=300&fit=crop&q=70&auto=format`;
/** Radius follows what the image IS: a playlist is a square tile, an
* artist is a circle, a podcast is a rounded app-icon-like square. */
const ITEMS: { id: string; title: string; meta: string; uri: string; rounded: ImageProps["rounded"]; alt: string }[] = [
{ id: "mix", title: "Late Night Drive", meta: "Playlist · 48 songs", uri: img("photo-1493225457124-a3eb161ffa5f"), rounded: "lg", alt: "Concert crowd under stage lights" },
{ id: "artist", title: "Solenne", meta: "Artist", uri: img("photo-1470225620780-dba8ba36b745"), rounded: "full", alt: "DJ at a mixing desk" },
{ id: "pod", title: "Signal & Noise", meta: "Podcast · Ep. 112", uri: img("photo-1478737270239-2f02b77fc618"), rounded: "2xl", alt: "Studio microphone" },
];
/** ImageRounded — a music app's "Pick up again" row, where each radius says
* what you're looking at. Tap one and it starts in the player bar. */
export function ImageRounded() {
const haptics = useHaptic();
const [playing, setPlaying] = React.useState("mix");
const now = ITEMS.find((i) => i.id === playing) ?? ITEMS[0]!;
return (
<Accent color="pink" className="w-full">
<View className="w-full gap-4">
<Text className="px-1 text-xl font-semibold tracking-tight">Pick up again</Text>
<View className="flex-row gap-3">
{ITEMS.map((it) => (
<Pressable
key={it.id}
onPress={() => {
haptics.selection();
setPlaying(it.id);
}}
className="flex-1 gap-2"
accessibilityRole="button"
accessibilityLabel={`Play ${it.title}`}
accessibilityState={{ selected: playing === it.id }}
>
<Image source={{ uri: it.uri }} rounded={it.rounded} aspectRatio={1} accessibilityLabel={it.alt} />
<View className={it.rounded === "full" ? "items-center" : undefined}>
<Text className="text-[15px] font-medium" numberOfLines={1}>{it.title}</Text>
<Text className="text-xs text-muted-foreground" numberOfLines={1}>{it.meta}</Text>
</View>
</Pressable>
))}
</View>
<View className="flex-row items-center gap-3 rounded-2xl bg-card p-2 pr-4">
<Image source={{ uri: now.uri }} rounded={now.rounded === "full" ? "full" : "md"} className="h-12 w-12" accessibilityLabel={now.alt} />
<View className="flex-1">
<Text className="text-[15px] font-medium" numberOfLines={1}>{now.title}</Text>
<Text variant="muted" numberOfLines={1}>{now.meta}</Text>
</View>
<Icon name="pause" size="md" color="primaryText" accessibilityLabel="Pause" />
</View>
</View>
</Accent>
);
} API reference
rounded "none" | "sm" +6
"none" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "full" Corner radius preset.
"md" aspectRatio number width / height ratio applied via style.
—fallback React.ReactNode Slot rendered when the image fails to load.
—hidePlaceholder boolean Hide the loading placeholder. Default false.
false alt string Alt text for the image — alias for accessibilityLabel. When neither is provided the label is left unset so the OS can decide what to announce.
className string — style RNImageProps["style"] —