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

app/components/home/Banner.tsx
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:

PropTypeDescription
src?stringImage URL. With no src, nothing is rendered.
altstringAlt text. Required.
priority?booleanAbove-the-fold image: loads eagerly with high fetch priority. Otherwise it loads lazily. Default: false.
aspectRatio?stringSuch 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?stringA different image at or below the mobile breakpoint, through a <picture> element.
mobileBreakpoint?numberMaximum width in px for mobileSrc. Default: 768.
noWrapper?booleanSkip 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.
  • aspectRatio adds a wrapper <div>. The style prop goes on that wrapper. Without aspectRatio (or with noWrapper) it goes on the <img> itself.
  • The src is rewritten to the CDN with the requested size, in server rendering and in the browser.
  • To make objectFit visible, give the image a size with className, for example h-full w-full.

Next

On this page