It is best practice for all web applications, to include images as a part of the user interface be it a landing page image, an avatar for a user profile, or even product images on an e-commerce site. We all know that size and format of an image play a vital role in app performance.
Next.js ensures serving images in the most optimized way by providing an image component. After launching the image component Next.js added lots of functionality like layout, loader, and onLoadingComplete props to improve image loading speed in the browser.
History of Image Component:
Why do we need an image component?
Next.js Image component provides many features. Let's discuss a few of them.
- Next.js image component improves speed and enhances performance. For each device, it serves an image in a different size, hence reducing the size of the image for smaller devices enhances performance.
- Images will be adjusted according to the device used.
- The web page loads more quickly since images are not loaded until they are visible in the viewport.
- Lazy loading.
- Support large format.
How to use Next.js Image component?
We don’t need to write an extra piece of code, Next.Js by default provides support image and image optimization for web applications.
To use the next.js image component there is only a prerequisite, next.js version should be greater or equal to 10.
The next.js image component is an extension of the HTML <img> element.
We can import the image component as follows:
In `next/Image` you must give the value of the below props:
src ( required ): It can be a statically imported file. In the other case, if you want to use absolute external URLs, you must add their domains in the next.config.js file as follows:
width ( required ): It is an integer value that tells the width of the image. It is a mandatory property except when we use fill layout property.
height ( required ): It is an integer value that tells the height of the image. It is a mandatory property except when we use fill layout property.
Layout: It controls how the image size responds to variations in viewport width. The layout is the optional props. It supports the following values:
- Intrinsic: It is the default behavior, which scales the image down to the width of the container, up to the image size. You can get an example of an intrinsic layout here.
- Fixed: It maintains the image's fixed width and height. You can get an example of a fixed layout here.
- Responsive: It adjusts the image's size to fit in the container. You can get an example of a responsive layout here.
- Fill: When you use fill layout, the image will increase its width and height to the dimensions of the parent element, given the parent element is relative. This is similar to the objectFit property. You can get an example of a fill layout here.
More to come, so stay tuned !!!!