Fixing Next.js Error: Use Image from ‘next/image’ Instead of ‘img’

Updated: January 1, 2024 By: Guest Contributor Post a comment

Understanding the Error

When you’re developing a project with Next.js and you come across the error message ‘Next.js Error: Do not use <img>. Use Image from ‘next/image’ instead,’ this is Next.js nudging you towards its built-in image optimization feature. Next.js prefers you use their Image component from the ‘next/image’ import because it includes performance optimizations like lazy loading, image resizing, and support for modern image formats.

Integrating the Image Component

To solve the error, you’ll need to swap out the standard HTML <img> tag for the next/Image component provided by Next.js. This means you must import the Image component from ‘next/image’ and use it to display your images. Next.js will then handle the optimization automatically.

Updating Existing Images

If you have existing <img> tags in your code, you’ll need to refactor them to use the Next.js Image component. Let’s say you previously had the following code with a standard <img> tag:

<img src="/path/to/image.jpg" alt="Description" width="500" height="300" />

You would update it to:

import Image from 'next/image';

function MyComponent() {
  return (
    <Image
      src="/path/to/image.jpg"
      alt="Description"
      width={500}
      height={300}
      layout="responsive"
    />
  );
}

Layout Property

The Next.js Image component also requires a ‘layout’ property. You can set it to ‘responsive’, ‘fill’, ‘fixed’, ‘intrinsic’, or ‘raw’. Choosing the right layout is important for how your image will resize along with its container. The ‘responsive’ option, which changes the size of the image as the viewport changes, is often the most useful.

Running a Complete Example

To better understand how to use the Image component, here’s a simple example you can run in a Next.js project:

import Image from 'next/image';

export default function HomePage() {
  return (
    <div>
      <h1>Welcome to My Next.js Page</h1>
      <Image
        src="/path/to/image.jpg"
        alt="Next.js Logo"
        width={256}
        height={144}
        layout="intrinsic"
      />
    </div>
  );
}

This code showcases a simple Next.js page that includes the optimized Image component to display an image file. Replace ‘/path/to/image.jpg’ with the actual path to your image file.

In summary, by updating your code to use the Next.js Image component, you’re not only complying with Next.js’ recommendation but also drastically improving your application’s performance and user experience.