Guide section
Basic React image fallback
Use onError to swap the failed image source for a placeholder. Clear the error handler first to avoid a loop if the fallback URL is ever unavailable.
function ProductImage({ src, alt }) {
const fallbackSrc =
"https://fallback.pics/api/v1/600x400?text=Product+Image";
return (
<img
src={src}
alt={alt}
onError={(event) => {
event.currentTarget.onerror = null;
event.currentTarget.src = fallbackSrc;
}}
/>
);
} Guide section
Create a reusable component
For production apps, put fallback behavior in one shared image component. That keeps product pages, profile cards, dashboards, and content previews consistent while avoiding repeated error-handler logic.
type FallbackImageProps = {
src?: string;
fallbackSrc?: string;
alt: string;
};
export function FallbackImage({
src,
fallbackSrc = "https://fallback.pics/api/v1/600x400?text=Image+Unavailable",
alt
}: FallbackImageProps) {
return (
<img
src={src || fallbackSrc}
alt={alt}
onError={(event) => {
event.currentTarget.onerror = null;
event.currentTarget.src = fallbackSrc;
}}
/>
);
} Guide section
Use different fallbacks by context
Product images, avatars, banners, and article thumbnails should not all use the same message. Choose a fallback URL that matches the role of the image.
- Product: /api/v1/600x600?text=Product+Image
- Avatar: /api/v1/avatar/200?text=JD
- Banner: /api/v1/banner/1200x400
- Missing media: /api/v1/600x400?text=Image+Unavailable