By Saheb Sutradhar - Updated On 05-03-2024
The Next.js Image component is a powerful tool that seamlessly integrates with Next.js applications. It extends the standard HTML <img>
element with additional features and optimizations, making it a versatile choice for handling images. Let’s dive into the details!
The Next.js Image component, also known as next/image
, offers several benefits:
Automatic Optimization: NextJS automatically optimizes images based on the device's resolution and size. This ensures fast loading times and a better user experience.
Lazy Loading: Images are loaded only when they come into the viewport, reducing initial page load time.
Responsive Images: The Image component allows you to create responsive images that adapt to different screen sizes.
Automatic Format Selection: Next.js selects the most appropriate image format (such as WebP) based on the user’s browser support.
Let’s explore the essential properties of the Next.js Image component:
The src property specifies the image source.
These properties are required unless you’re using statically imported images or images with the fill
property.
Let’s explore an example of using the width
and height
properties with the Next.js Image Component:
import Image from 'next/image';
export default function MyPage() {
return (
<div>
<Image
src="/product-image.jpg"
alt="Product Image"
width={800}
height={600}
/>
</div>
);
}
The alt
property describes the image for screen readers and search engines. It’s also the fallback text if images are disabled or an error occurs while loading. Provide meaningful text that conveys the image’s purpose.
The loader
property allows you to define a custom image loader function. You can use this to handle image loading and transformations.
Let’s explore an example of using a custom image loader with the Next.js Image Component. The loader
property allows you to define your own logic for loading images. Here’s how you can create a custom loader function:
// Custom image loader function
const myImageLoader = ({ src, width, quality }) => {
// Construct the image URL based on your requirements
return `https://my-cdn.com/${src}?w=${width}&q=${quality || 75}`;
};
// Usage in your component
import Image from 'next/image';
export default function MyPage() {
return (
<div>
<Image
loader={myImageLoader}
src="/product-image.jpg"
alt="Product Image"
width={800}
height={600}
/>
</div>
);
}
In this example:
"https://my-cdn.com/"
with the actual base URL of your image server.src
parameter represents the relative path to the image file.width
and quality
parameters are used to customize the image dimensions and compression level.By implementing a custom loader, you have fine-grained control over how images are loaded and transformed in your Next.js application.
The fill
property determines whether the image should fill its container. Set it to true
for images that need to occupy the available space.
Here’s an example of how to use the Image
component with the fill
property:
// Import the necessary components
import Image from 'next/image';
// Example usage of the Image component
export default function MyPage() {
return (
<div>
{/* Example 1: Using an absolute path */}
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
{/* Example 2: Using a statically imported image */}
{/* Make sure to import your image file */}
{/* For example, if you have 'logo.svg' in your 'public' folder */}
<Image
src={logo}
width="100px"
height="200px"
/>
</div>
);
}
In the above examples:
/profile.png
) for the image source. You can also use an external URL or an internal path depending on the loader
prop.width
and height
properties define the rendered dimensions of the image.alt
attribute provides a description for screen readers and search engines.Use the sizes
property to specify responsive image sizes. For example: sizes="(max-width: 768px) 100vw, 33vw"
.
Here’s an example of how to use the sizes
property along with other relevant properties:
// Import the necessary components
import Image from 'next/image';
// Example usage of the Image component
export default function MyPage() {
return (
<div>
{/* Example 1: Using an absolute path */}
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
sizes="(max-width: 768px) 100vw, 33vw"
/>
{/* Example 2: Using a statically imported image */}
{/* Make sure to import your image file */}
{/* For example, if you have 'logo.svg' in your 'public' folder */}
<Image
src={logo}
width="100px"
height="200px"
sizes="(min-width: 768px) 80px, 60px"
/>
</div>
);
}
In the above examples:
/profile.png
) for the image source. You can also use an external URL or an internal path depending on the loader
prop.width
and height
properties define the rendered dimensions of the image.alt
attribute describes screen readers and search engines.sizes
property specifies different image sizes based on the viewport width. In the first example, the image will be 100% of the viewport width on screens up to 768px wide, and 33% of the viewport width beyond that. In the second example, the image will be 80px wide on screens wider than 768px and 60px wide on smaller screens.The quality
property controls image compression. Set it to an integer between 1 and 100 (higher values mean better quality).
// Example usage
import Image from 'next/image';
export default function MyPage() {
return (
<div>
<Image
src="/your-image-source.png"
width={500}
height={500}
alt="Logo"
quality={100}
/>
</div>
);
}
The priority
property indicates whether the image should be loaded immediately (useful for critical images).
// Import the necessary components
import Image from 'next/image';
// Example usage with priority
export default function Home() {
return (
<>
<h1>My Homepage</h1>
<Image
src="/me.png"
alt="Picture of the author"
width={500}
height={500}
priority
/>
<p>Welcome to my homepage!</p>
</>
);
}
In this example:
priority
to true
for the /me.png
image.Specify a placeholder strategy using the placeholder
property. For instance, "blur"
and blurDataURL
(a base64-encoded image) that represents the blurred version of your image.
// Import the necessary components
import Image from 'next/image';
// Example usage with blur placeholder
export default function MyPage() {
return (
<div>
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
placeholder="blur"
blurDataURL="/assets/image-placeholder.png"
/>
</div>
);
}
Customize the image style using the style
property (e.g., objectFit: "contain"
).
Handle image loading and error events with these properties. Suppose you want to create a custom Image
component that handles loading and error states. Here’s an example:
import Image from 'next/image';
import React, { useState } from 'react';
function CustomImage({ src, alt }) {
const [imageSrc, setImageSrc] = useState(src);
const handleImageError = () => {
// Set a fallback image source in case of an error
setImageSrc('/assets/image-error.png');
};
return (
<Image
src={imageSrc}
alt={alt}
onError={handleImageError}
placeholder="blur"
blurDataURL="/assets/image-placeholder.png"
/>
);
}
// Usage:
function MyPage() {
return (
<div>
<CustomImage src="/profile.png" alt="Picture of the author" />
</div>
);
}
Set the loading
property to "lazy"
for lazy loading.
<Image src={img} alt="A cool image" loading="lazy" />
To use the Next.js Image Component with external images, follow these steps:
In your next.config.js
file, add the domains of the external images you want to use. This ensures that only images from specified domains can be served through the Next.js Image Optimization API. For example:
// next.config.js
module.exports = {
images: {
domains: ['example.com', 'cdn.example.com'],
},
};
Replace 'example.com'
and 'cdn.example.com'
with the actual domains of your external images
Import the Image
component from 'next/image'
in your desired component.
Add the JSX syntax for the Image
component with the required properties (src
, width
, and height
). For example:
import Image from 'next/image';
export default function MyPage() {
return (
<div>
<Image
src="https://example.com/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
);
}
Replace "https://example.com/profile.png"
with the actual URL of your external image.
Remember that Next.js handles image optimization automatically, ensuring fast loading times and a better user experience. Enjoy using the Next.js Image Component for your external images.
Trending Posts
Create Input Floating Label in CSS and HTML...
CSS Card Hover Effects: Make Your Website Stand Ou...
Create a Rotate Image Gallery with HTML and CSS...
CSS Hover Effect | Web Development...
How to create MongoDB Free cloud Database - Atlas ...
Learn how to create CSS Button RGB Animation...
Create Responsive Sidebar with React JS and tailwi...
Build a JavaScript Carousel Slider With Example...
How to Disable the Submit Button in Formik...
How to Use Bootstrap 5 in Next.js...
codelearningpoint © 2024