In this article I will guide you in how to use the picture element in Next.js.
If you tried using the picture element directly in Next.js, you probably already noticed your image has no optimizations. To fix it we'll be using a fairly new function from Next.js: getImageProps.
INFO
At the time of writing this article, I'm using:
Next.js 14.2.14
Creating the ResponsiveImage component
On your components folder create a new component file, I'll be naming mine: ResponsiveImage.tsx.
Import getImageProps and create the base for the component:
import { getImageProps } from 'next/image';
export const ResponsiveImage = () => {
return <></>;
};
Now I'm going to add some types for this component's prop, I'm going with a pretty basic type for brevity.
// Import base image props type
import { getImageProps, type ImageProps } from 'next/image';
// We'll be using src as the source of truth for the image
type ResponsiveImageProps = ImageProps & {
desktopSrc: string;
};
export const ResponsiveImage = ({
// Extract src and desktopSrc from props spread
src,
desktopSrc,
...props
}: ResponsiveImageProps) => {
return <></>;
};
Moving forward, we'll now extract the props from the sources and apply common props.
import { getImageProps, type ImageProps } from 'next/image';