What is the Next.js Image Component

By Saheb Sutradhar - Updated On 05-03-2024

What is the Next.js Image Component

 

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!

What is the Next.js Image Component?

The Next.js Image component, also known as next/image, offers several benefits:

  1. Automatic Optimization: NextJS automatically optimizes images based on the device's resolution and size. This ensures fast loading times and a better user experience.

  2. Lazy Loading: Images are loaded only when they come into the viewport, reducing initial page load time.

  3. Responsive Images: The Image component allows you to create responsive images that adapt to different screen sizes.

  4. Automatic Format Selection: Next.js selects the most appropriate image format (such as WebP) based on the user’s browser support.

Key Properties of the Image Component

Let’s explore the essential properties of the Next.js Image component:

1. src (Required)

The src property specifies the image source.

  • A statically imported image file.
  • An absolute external URL.
  • An internal path (depending on the loader prop).

2. width and height (Required)

  • width: Represents the rendered width in pixels.
  • height: Represents the rendered height in pixels.

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>
  );
}

3. alt (Required)

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.

4. loader

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:

  • Replace "https://my-cdn.com/" with the actual base URL of your image server.
  • The src parameter represents the relative path to the image file.
  • The 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.

5. fill

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:

  • We use an absolute path (/profile.png) for the image source. You can also use an external URL or an internal path depending on the loader prop.
  • The width and height properties define the rendered dimensions of the image.
  • The alt attribute provides a description for screen readers and search engines.

6. sizes

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:

  • We use an absolute path (/profile.png) for the image source. You can also use an external URL or an internal path depending on the loader prop.
  • The width and height properties define the rendered dimensions of the image.
  • The alt attribute describes screen readers and search engines.
  • The 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.

7. quality

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>
  );
}

8. priority

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:

  • We set priority to true for the /me.png image.
  • The image will be loaded with high priority, improving the overall user experience.

9. placeholder

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>
  );
}

10. style

Customize the image style using the style property (e.g., objectFit: "contain").

11. onLoad and onError

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>
  );
}

12. loading

Set the loading property to "lazy" for lazy loading.

<Image src={img} alt="A cool image" loading="lazy" />

How do I use Next.js Image Component with external images?

To use the Next.js Image Component with external images, follow these steps:

Step 1- Configure External Domains:

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

Step 2- Use the Image Component

Import the Image component from 'next/image' in your desired component.

Add the JSX syntax for the Image component with the required properties (srcwidth, 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.

 

codelearningpoint © 2024