Next.js <Image> (Component)
Introduction:
An image component in Next.js is a pre-optimized and declarative element used for efficiently displaying images on web pages.
Benefits:
- Automatic image optimization for improved performance.
- Responsive images for different device sizes.
- Lazy loading to reduce initial page load time.
- On-the-fly transformations for image resizing, cropping, and filters.
- Automatic selection of optimal image formats.
- Placeholder support for smoother loading and layout consistency.
How to use:
import Image from 'next/image'
The Image Component requires the following properties: src, width, height, and alt.
What's interesting to note is that the next/image automatically generates width, height, and blurDataURL values for statically imported images. These values are used to prevent Cumulative Layout Shift(CLS) before the image is finally loaded. It's also possible to pass these values explicitly.
export default function Page() { return ( <div> <Image src="/sample.png" width={500} height={500} alt="Sample Picture" /> </div> ) }
Note: You should always add the width and height props in the image component when using remote images because NextJS cannot determine the dimension of the image during the build process for proper page rendering to prevent layout shifts.
Optional Properties:
loader
A loader is a function returning a URL string for the image, given the following parameters:
- src
- width
- quality
Here is an example of using a custom loader:
'use client' import Image from 'next/image' const imageLoader = ({ src, width, quality }) => { return `https://example.com/${src}?w=${width}&q=${quality || 75}` } export default function Page() { return ( <Image loader={imageLoader} src="sample.png" alt="Sample Picture" width={500} height={500} /> ) }
Alternatively, you can use the loaderFile configuration in next.config.js to configure every instance of next/image in your application, without passing a prop.
fill
fill={true} // {true} | {false}
When set to true, the image will fill its parent element without explicitly defining width and height. The default image fit behavior stretches the image to fit the container.
sizes
A string containing information on how wide the image will be at certain breakpoints. The size value has a significant impact on performance for pictures that use fill or are styled to have a responsive site. For example, if you know your styling will cause an image to be full-width on mobile devices, in a 2-column layout on tablets, and in a 3-column layout on desktop displays, you should include a sizes property such as the following:
import Image from 'next/image' export default function Page() { return ( <div className="grid-element"> <Image fill src="/example.png" sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" /> </div> ) }
These example sizes could have a dramatic effect on performance metrics. Without the 33vw sizes, the image selected from the server would be 3 times as wide as it needs to be. Because file size is proportional to the square of the width, without sizes the user would download an image that's 9 times larger than necessary.
quality
quality={75} // {number 1-100}
The quality of the optimized image is an integer between 1 and 100, where 100 is the best quality and therefore largest file size. Defaults to 75.
priority
priority={false} // {false} | {true}
Setting the "priority" property to true for an image makes it a high priority and reloads it, disabling lazy loading. The default value is false.
placeholder
placeholder = 'empty' // {empty} | {blur}
The "placeholder" property determines the type of placeholder used during image loading. It can be set to "blur" or "empty" (default).
Try it out:
- Demo the blur placeholder
- Demo the shimmer effect with blurDataURL prop
- Demo the color effect with blurDataURL prop
style
const imageStyle = { borderRadius: '50%', border: '1px solid #fff', } export default function ProfileImage() { return <Image src="..." style={imageStyle} /> }
Keep in mind that the necessary width and height props can interact with your styling. If you use styling to change an image's width, you should also change its height to auto to keep the image's inherent aspect ratio. Otherwise, your image will be deformed.
loading
This property is only meant for advanced use cases. Switching an image to load with eagerness will normally hurt performance. We recommend using the priority property instead, which will eagerly pre-load the image.
loading = 'lazy' // {lazy} | {eager}
The loading behavior of the image. Defaults to lazy.
When lazy, defer loading the image until it reaches a calculated distance from the view port.
When eager, load the image immediately.
onLoadingComplete
'use client' <Image onLoadingComplete={(img) => console.log(img.naturalWidth)} />
A callback method is called after the image has finished loading and the placeholder has been removed. The callback function will be invoked with a single parameter, a reference to the underlying image> element.
Domain
The domain configuration can be used to provide a list of allowed hostnames for external images. This helps to prevent your application from malicious users. For example, the following configuration will ensure your external images starts with s3.amazonaws.com. Any other protocol or unmatched hostname will respond with 400 Bad Requests.
module.exports = { images: { domains: ['s3.amazonaws.com'] }, }