Image
An image that lazy-loads, resizes through the CDN and reserves space to avoid layout shift.
Use Image instead of <img> for store images such as banners and product photos. It lazy-loads, asks the CDN for a suitable size and can reserve the image's space so the page does not jump while it loads.
Example
import { Image } from '@salla.sa/twilight-theme-engine/common';
export function Banner({ url, alt, mobileUrl }: { url: string; alt: string; mobileUrl?: string }) {
return (
<Image
src={url}
mobileSrc={mobileUrl}
alt={alt}
aspectRatio="16/9"
sizes="100vw"
srcSetWidths={[480, 768, 1200]}
priority
/>
);
}API
ImageProps extends the standard <img> attributes (className, width, height, sizes, srcSet and the rest). Added or changed props:
| Prop | Type | Description |
|---|---|---|
src? | string | Image URL. With no src, nothing is rendered. |
alt | string | Alt text. Required. |
priority? | boolean | Above-the-fold image: loads eagerly with high fetch priority. Otherwise it loads lazily. Default: false. |
aspectRatio? | string | Such as "16/9". Wraps the image in a box of that ratio to prevent layout shift. |
objectFit? | "cover" | "contain" | "fill" | "none" | "scale-down" | Adds an object-* class. Default: "cover". |
mobileSrc? | string | A different image at or below the mobile breakpoint, through a <picture> element. |
mobileBreakpoint? | number | Maximum width in px for mobileSrc. Default: 768. |
noWrapper? | boolean | Skip the aspect-ratio wrapper element. Default: false. |
srcSetWidths? | readonly number[] | CDN widths for a generated srcset. Pair with sizes. |
Gotchas
- Mark only the main image above the fold as
priority. Everything else should stay lazy. aspectRatioadds a wrapper<div>. Thestyleprop goes on that wrapper. WithoutaspectRatio(or withnoWrapper) it goes on the<img>itself.- The
srcis rewritten to the CDN with the requested size, in server rendering and in the browser. - To make
objectFitvisible, give the image a size withclassName, for exampleh-full w-full.
Next
ProductCardusesImagefor its photo.Linkfor navigation.- Styling