Skip to content

Code components - Responsive images

The next-image-standalone library provides automatic image optimization, responsive behavior, and modern loading techniques for code components.

import Image from 'next-image-standalone';
const MyComponent = ({ photo }) => {
return (
<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
/>
);
};
export default MyComponent;

Image prop includes all the required props.

<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
/>

Image can also be used with static values but this is not recommended as it will not result in responsive image variants being generated.

<Image src="/profile.png" alt="Picture of the author" width={500} height={500} />

A boolean that causes the image to fill the parent element, which is useful when the width and height are unknown.

The parent element must assign position: relative, position: fixed, or position: absolute style.

<div style={{ position: 'relative', width: '300px', height: '500px' }}>
<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
fill
style={{
objectFit: 'cover', // cover, contain, none, scale-down, fill
}}
/>
</div>

Defines which image sizes to download at different breakpoints. The value of sizes will affect performance for images using fill or those which are styled to have a responsive size.

<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>

A placeholder to use while the image is loading to improve perceived performance. Possible values are empty, or data:[dataUrl].

<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
placeholder="blur"
/>

Allows passing CSS styles to the underlying image element.

<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
style={{
width: '100%',
height: 'auto',
}}
/>

A callback function that is invoked once the image is completely loaded and the placeholder is removed.

<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
onLoad={(e) => console.log(e.target.naturalWidth, e.target.naturalHeight)}
/>

A callback function that is invoked if the image fails to load.

<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
onError={(e) => console.error('Image failed to load')}
/>

The loading behavior of the image. Defaults to lazy.

When lazy, defer loading the image until it reaches a calculated distance from the viewport.

When eager, load the image immediately.

<Image
src={photo.src}
alt={photo.alt}
width={photo.width}
height={photo.height}
loading="eager"
/>