How to use Image component in Next.js with unknown width and height

Since version 10, Next.js comes with the built-in Image component which provides the feature of image optimization and resizing image responsively. I like it a lot and I've been using it across my website for images with fixed size. According to the official documentation, width and height are required props unless it's for layout=fill.

Now, I would like to use Image component even when I don't know width and height ahead of time. I have blog resources that come from a CMS where the exact size of image is unknown. In this case, is there any way I could use Image component?

Any help would be appreciated.


Solution 1:

Yeah, you could use it with the layout=fill option you mentioned.

On this case, you're gonna need to set an "aspect ratio" for your images

<div style={{ position: "relative", width: "100%", paddingBottom: "20%" }} >
  <Image
    alt="Image Alt"
    src="/image.jpg"
    layout="fill"
    objectFit="contain" // Scale your image down to fit into the container
  />
</div>

You can use objectFit="cover" too and it'll scale your image up to fill all the container.

The downside of this approach is that is gonna be attached to the width you specify, it could be relative such as "100%" or absolute e.g. "10rem", but there's no way to set like an auto width and height based on the size of your image, or at least no yet.