How to usenext/Image Component in Next.js

In this approach, we are using the next/image component in a Next.js application to load an external image from a specified URL. This component optimizes image loading and provides control over dimensions.

Example: The below example uses the next/Image Component to Load NextJS Images from an External URL.

JavaScript
//page.js

"use client";
import React, { useState } from 'react';
import Image from 'next/image';
const Page = () => {
   const [showImage, setShowImage] = useState(false);
   const btnFn = () => {
     setShowImage(true);
   };
  return (
    <div>
      <h1>Approach 1: Using next/Image Component</h1>
      { !showImage && (
         <button onClick={btnFn}>Load Image</button>
        )
      }
      {  showImage && (
         <Image src=
  "https://media.w3wiki.org/wp-content/uploads/20230816191453/gfglogo.png"
          alt="External Image"
          unoptimized
          width={300}
          height={200}
        />
      )}
    </div>
  );
};
export default Page;

Step to run the application: Now run the application with the below command:

npm run dev

Output:

How to Load NextJS Images from an External URL

In Next.js, loading external URL images is important because it allows developers to incorporate dynamic content and enrich user experiences by displaying images from various sources seamlessly within their applications.

In this article, we will explore two different approaches to loading NextJS Images from an External URL.

Table of Content

  • Using next/Image Component
  • Using an <img> Tag

Similar Reads

Steps to Create the Next.js Application

Step 1: Set up React Project using the Command:...

Approach 1: Using next/Image Component

In this approach, we are using the next/image component in a Next.js application to load an external image from a specified URL. This component optimizes image loading and provides control over dimensions....

Approach 2: Using an Tag

In this approach, we are using React state (useState) to manage the image source (imageSrc) dynamically based on user button clicks, allowing the loading of external images into a tag within a Next.js application....