Joint session with Vercel: How to build intelligent storefronts (May 15th)

The best Next.js & Sanity <Image/> Component

Okay, well it might be at least in the top 3. Using getDimensions and optimising the hell out of your images, check out this snippet

By Roboto Studio & Jono Alford


Size is dictated by image dimensions

import { ReactElement } from 'react';
import Image from 'next/image';
import { getImageDimensions } from '@sanity/asset-utils';
import { urlFor } from '~/lib/sanity';

export const IdealImage = ({ image }): ReactElement => {
  const alt = image?.alt ?? "An image without an alt, whoops";
  return (
    <div>
      ...
      {image?.asset && (
        <Image
          src={urlFor(image).url()}
          alt={alt}
          width={getImageDimensions(image).width}
          height={getImageDimensions(image).height}
          placeholder="blur"
          blurDataURL={urlFor(image).width(24).height(24).blur(10).url()}
          sizes="
            (max-width: 768px) 100vw,
            (max-width: 1200px) 50vw,
            40vw"
        />
      )}
      ...
    </div>
  );
};

Size is dictated by pre-defined size

import { ReactElement } from 'react';
import Image from 'next/image';
import { getImageDimensions } from '@sanity/asset-utils';
import { urlFor } from '~/lib/sanity';

export const IdealImage = ({ image }): ReactElement => {
  const alt = image?.alt ?? "An image without an alt, whoops";
  return (
    <div>
      ...
      {image?.asset && (
        <Image
          src={urlFor(image).width(1920).height(1080).dpr(2).url()}
          alt={alt}
          width={1920}
          height={1080}
          placeholder="blur"
          blurDataURL={urlFor(image).width(24).height(24).blur(10).url()}
          sizes="
            (max-width: 768px) 100vw,
            (max-width: 1200px) 50vw,
            40vw"
        />
      )}
      ...
    </div>
  );
};

If you're looking for a quick and easy snippet for implementing an image with Next.js, this is what you're looking for. There are two versions:

  1. A version where the image size dictates the size of the image on the page (this is what you would use if you want functionality closest to a default <img> tag).
  2. A version where the image adjusts using a pre-defined size. E.g. 1920px by 1080px (16:9 ratio).

One thing to notice is the dpr(value). If you're setting it to two, it's basically retina-ready but can massively impact performance. Think long and hard about adding this, but I've added it in for the hell of it.

Fancy trying to squeeze the very last drop out of your website performance? Get in touch with us; we've: been there, seen it, got the T-shirt with most questions.

Contributors

Roboto Studio

The best editorial experiences on the web

Visit Roboto Studio's profile

Jono Alford

Founder @ Roboto Studio - The Sanity & Next.js experts

Visit Jono Alford's profile