|Kit

Image

An img that holds its box while it loads, shows a blurred, colored or skeleton placeholder, and crossfades in. Takes a CDN loader for responsive srcsets and falls back cleanly when loading fails.

Image renders two elements. A root <span> owns the box: its aspect ratio, its radius and the clipping. It also paints the placeholder. The <img> inside it fades in over the placeholder once it has loaded and decoded, so you never see a half-painted frame. The placeholder is plain CSS, so it's already in the server HTML: either a color, or a tiny data: image blurred through an SVG filter. With neither, the box pulses like a Skeleton.

import { Image } from '@42-central/ui-react/image';

<Image src={photo.url} alt={photo.description} ratio="3/2" placeholder={photo.blur} className="w-full" />

Playground

Component

Loading preview

Props

Code

<Component
  position="center"
  ratio="3/2"
  src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=960&q=70"
  alt="Snow-capped mountains above the clouds"
  placeholder="#4b5f80"
/>

Full prop browser

Status

The status is empty (no src), loading, loaded or error. It's set as data-state on both the root and the <img>, and reported through onStatusChange. The status is tracked per source: when src changes, the new source reads as loading from its very first render, and a source that has already loaded reads as loaded again straight away. This demo loads through a deliberately slow endpoint, so you can watch every change.

A mountain lake at dawn
Statusloading

Replay to log the changes

Code

const [status, setStatus] = useState<ImageStatus>('loading');

<Image
  src={slowUrl}
  alt="A mountain lake at dawn"
  ratio="3/2"
  placeholder={blurDataUri}
  onStatusChange={setStatus}
/>

Style the states from CSS with data-[state=loaded]:… on the root, or with classNames.image on the image.

Placeholders

placeholder takes a CSS color, or a data: URI. A data URI is drawn into an SVG through an feGaussianBlur and used as the root's background-image, so a 10px thumbnail scales up into a soft wash rather than a mosaic. This is the same technique next/image uses, and it needs no dependency. Leave placeholder out, and the box pulses with the Skeleton tokens.

Snow-capped mountains above the cloudsBlurred data URI
Snow-capped mountains above the cloudsColor
Snow-capped mountains above the cloudsNone: skeleton

Code

<Image src={src} alt="…" ratio="3/2" placeholder="data:image/png;base64,iVBORw0KGgo…" />
<Image src={src} alt="…" ratio="3/2" placeholder="#4b5f80" />
<Image src={src} alt="…" ratio="3/2" />

Generate the data URI where the image is stored or built (a CMS field, or a build step with sharp or plaiceholder), at about 10px wide. The two in this page are 254 bytes each. A color works well when you already have a dominant color for the image.

The placeholder is removed once the image is fully opaque, not when it starts fading in. Removing it at the start would flash the page through the fade. Removing it afterwards means it never shows through a transparent PNG.

Sizing

Reserve the box before the image arrives, or the page shifts when it does. There are two ways:

  • width and height: a fixed-size image. The root takes width in pixels, gets the aspect ratio from both values, and still shrinks with max-width: 100%.
  • ratio: a fluid image. Give the root a width with className (w-full, a grid cell…) and ratio sets the height. ratio takes a number (16 / 9) or the CSS string form ("16/9"), and it overrides the shape width and height would give.
A mountain lake at dawnA mountain lake at dawnA mountain lake at dawn

Code

<Image src={src} alt="…" ratio="1/1" className="w-full" />
<Image src={src} alt="…" ratio="4/3" className="w-full" />
<Image src={src} alt="…" ratio="16/9" className="w-full" />

A consumer w-* class always wins over width, so width={1200} height={800} className="w-full" gives a fluid image with the right shape and a srcset capped for 1200px.

Fit and position

fit is object-fit, and cover by default. position picks which part of the image stays visible when it's cropped. It accepts any CSS object-position value. The logical keywords start, end, top-start, top-end, bottom-start and bottom-end follow the text direction (see Right-to-left). The blurred placeholder uses the same fit and position as the image, so the crossfade doesn't shift the picture.

Snow-capped mountains above the cloudsSnow-capped mountains above the cloudsSnow-capped mountains above the clouds

Code

<Image src={src} alt="…" ratio="1/1" fit="cover" />
<Image src={src} alt="…" ratio="1/1" fit="contain" />
<Image src={src} alt="…" ratio="1/1" position="top" />

Radius

radius uses the kit's radius scale and defaults to xs, like a button or an input. Use radius="none" for a square edge, for example when the image sits flush against a card's border.

A mountain lake at dawnA mountain lake at dawnA mountain lake at dawnA mountain lake at dawnA mountain lake at dawn

Code

<Image radius="none" … />
<Image radius="xs" … />
<Image radius="md" … />
<Image radius="xl" … />
<Image radius="full" … />

Loader

The kit doesn't resize images. A loader tells it how your image service builds the URL for one width, and Image turns that into a srcset:

Propssrcset
No loaderNone: src is used as is
loader + sizesw descriptors from 16px to 3840px, up to twice width when you set it. The browser picks one from sizes
loader + width1x and 2x
loader aloneAs with sizes="100vw"
Snow-capped mountains above the clouds

Loading…

Code

import { Image, type ImageLoader } from '@42-central/ui-react/image';

const unsplash: ImageLoader = ({ src, width, quality = 75 }) =>
  `${src}?w=${width}&q=${quality}&auto=format`;

<Image
  src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4"
  alt="Snow-capped mountains above the clouds"
  loader={unsplash}
  sizes="(min-width: 768px) 640px, 100vw"
  quality={70}
  ratio="16/9"
/>

The loader is passed per image. Wrap Image in your own component when every image in an app goes through the same service. fallbackSrc never goes through the loader, so a misconfigured loader can't break the fallback too.

Priority

Set priority on the image that's likely to be the largest thing in the first viewport, such as a hero or the main product photo. That image:

  • is preloaded from the document head through ReactDOM.preload, with its srcset and sizes,
  • is fetched eagerly with fetchpriority="high",
  • is never hidden and never fades in.
<Image src={hero.url} alt={hero.alt} priority loader={cdn} sizes="100vw" ratio="21/9" className="w-full" />

Every other image is loading="lazy" and decoding="async". Leave priority off everywhere else: preloading everything is the same as preloading nothing.

Why priority skips the fade

The fade needs React: the image stays transparent until React has hydrated and seen it load. So a non-priority image appears at hydration or at load, whichever comes later. The placeholder makes that wait look like loading rather than a blank space. The largest image in the first viewport is the one your LCP is measured on, so it should never wait for JavaScript. That's what priority does.

Fallbacks

When src fails, fallbackSrc is tried once, as is. When that fails too, or when there's no src at all, the root shows the fallback: an icon by default, or any node you pass. A failed source is remembered, so the fallback never loops.

When the image fails and you passed a placeholder, the placeholder stays under the fallback: a blur stays blurred and a color stays the color, as a hint of what should be there. The fallback's content then sits on a small chip, so it stays legible over a light or dark blur in either theme. Without a placeholder, the fallback is a plain translucent surface. The skeleton pulse is never kept, because a shimmer means "loading", not "failed". With no src at all there's nothing to hint at, so the placeholder isn't shown.

A mountain lake at dawnfallbackSrc
A mountain lake at dawnBlur kept
A mountain lake at dawnColor kept, custom node
A mountain lake at dawnNo placeholder
No src

Code

<Image src={broken} fallbackSrc="/placeholder.jpg" alt="A mountain lake at dawn" ratio="1/1" />
<Image src={broken} alt="A mountain lake at dawn" ratio="1/1" placeholder={blurDataUri} />
<Image src={broken} alt="A mountain lake at dawn" ratio="1/1" placeholder="#4b5f80" fallback={<span>Photo unavailable</span>} />
<Image src={broken} alt="A mountain lake at dawn" ratio="1/1" />
<Image alt="Profile photo" ratio="1/1" placeholder="#4b5f80" />

Icons

icons replaces the kit's icons. Image has one, fallback: the broken picture drawn when there's nothing to show. Set it to null to leave the box empty, so a kept placeholder shows on its own, with no chip. A fallback node wins over icons.fallback: use fallback for content, such as a line of text, and icons to swap only the glyph. The default draws the kit's 1.5px line; yours is drawn as given, so add className={iconStroke} (from @42/ui-react) to match it.

A mountain lake at dawnCustom icon
Custom icon, no placeholder
A mountain lake at dawnnull: the blur alone

Code

<Image src={broken} alt="…" ratio="1/1" placeholder="#4b5f80" icons={{ fallback: <CameraOff className={iconStroke} /> }} />
<Image alt="…" ratio="1/1" icons={{ fallback: <MountainSnow className={iconStroke} /> }} />
<Image src={broken} alt="…" ratio="1/1" placeholder={blurDataUri} icons={{ fallback: null }} />

Right-to-left

position="start" crops to the inline-start edge: the left in a left-to-right page, and the right in a right-to-left one. The page's direction toggle flips every demo on this page; this one shows both directions at once.

Snow-capped mountains above the cloudsdir="ltr": crops to the left
Snow-capped mountains above the cloudsdir="rtl": crops to the right

Code

<div dir="ltr"><Image src={src} alt="…" ratio="1/1" position="start" /></div>
<div dir="rtl"><Image src={src} alt="…" ratio="1/1" position="start" /></div>

API

Prop

Type

Any other <img> attribute (crossOrigin, referrerPolicy, draggable, onLoad, onError…) is passed to the <img>. loading, fetchPriority, srcSet and decoding are set by the component.

No asChild: Image renders two elements, and a child could only replace one of them.

Accessibility

  • alt is required. Leaving it out is a type error. Describe what the image shows in its context, or pass alt="" when the image is decorative, so screen readers skip it.
  • The fallback keeps the label. When the image fails or there's no src, the fallback has role="img" and aria-label set to alt, so the image is still announced. With alt="", the fallback is aria-hidden.
  • No broken-image icon or alt-text flash. The <img> is transparent while it loads, and its text is transparent too, so a browser never paints its alt text over the placeholder. A failed <img> is removed and replaced by the fallback.
  • Not interactive. Image has no role of its own and takes no focus. Wrap it in a link or a button when it should do something, and give that the accessible name.
  • Reduced motion. With prefers-reduced-motion: reduce, the image appears without a fade and the skeleton doesn't pulse.
  • Forced colors. Backgrounds are dropped in Windows High Contrast, so the fallback gets a CanvasText border, and its icon uses the text color. Over a kept placeholder, the chip behind the icon becomes an opaque Canvas surface.
  • Right-to-left. The box uses logical properties only, and position's start/end keywords follow the direction.

Internationalization

Image renders no text of its own, so it has no translations prop. Its only user-facing string is alt, which is your content. Translate it like the rest of the page, for example from your message catalog:

<Image src={photo.url} alt={t('gallery.photoAlt', { place: photo.place })} ratio="3/2" />

A custom fallback that contains text is your content too, so translate it the same way.

Changelog

v0.20.0
  • New Image: an <img> that fades in once decoded over a color, blurred data: or skeleton placeholder painted in the SSR HTML, with a CDN loader that builds srcset, priority, fallbackSrc, a required alt, ratio, radius, RTL-aware position and onStatusChange

    #345

On this page