avatar
Official Post
NextJs
16 Apr 2023

Customizing Next JS Image Component

thumbnail

Let’s see how we can customize the NextJs Image component. How to give 100% width and height to NextJs Image component? How to use custom styles in NextJs Image component? How we can use images from an unknown host / unconfigured host in NextJs? How to use custom styles in NextJs Image component?

How to use images from the unknown or unconfigured host in next js?

NextJs always recommend you use the next/Image component for better image optimization of your images. When you use any image with next/Image you have to configure the host of that image in next.config.js. Something like -

// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
        port: '',
        pathname: '/account123/**',
      },
    ],
  },
}

And if you use regular <img/> of the HTML NextJs throws warnings on production. Then how can we do that?

Here's the solution, you can use the Image component with the 'unoptimized' property of the next/Image.

<Image
    unoptimized
    src={"https://any-unknown-host/image.png"}
    width={100}
    height={100}
    alt={"image"}
/>

Now, NextJs will not throw any warning but image optimization will not happen.

How to use custom styles in next/Image?

NextJs Image component have a prop called style, with this you can use custom css for your image. Ex.

  <Image
      src={"/image.jpg"}
      width={100}
      height={100}
      style={{
        display:"block",
        objectFit:"cover"
      }}
      alt="image"
  />

NOTE: If you use width and height in styles then you should always give max resolutions of the your images. See the following example.

How to give 100% width and height to NextJs Image component?

NextJs Image component doesn't allow you to use any other values in the width and height prop instead of integers representing pixels. You can use style prop for that, but still, there is the problem of what value you should pass into the width and height prop because it will throw errors. Here’s the trick for that.

  <Image
      src={"/image.jpg"}
      width={7680}
      height={4320}
      style={{
        width: "100%",
        height: "100%"
      }}
      alt="image"
  />

In the above example, the width and height prop is the max resolution of the image. Whenver you use height and width in styles you must specify max resolutions of your images. If you don't know then you can use 7680 × 4320 for width and height respectively is the 8k standard resolution also you can use 4k or 2k. Now in styles, you can use anything for width and height like vh, vw, px, auto, % in styles prop. No errors will be thrown and image will be rendered properly as you want.