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

Next JS Mohaimen Khalid

Problem:

Sometimes we tried to add Image component without width and height like html img tag. So we got an error message width and height are required.  Then we would like to use Image component without known height and width. Lets discus how to fix this issue?


Solution:

First we have to know how next js <Image /> component works.  The component <Image /> requires some props like src, width, height. The <image /> component optionally accepts the following properties.

<Image
        width={500}
        height={500}
        src={imgSrc}
        alt="images name"
      />

width and height property value must in pixel value and also integer value with not unit like "px".  So we can said that you have to must provide height and width props with the <Image /> component. 

If you don't want to use width and height then you can can use Layout props. The layout behavior of the image as the viewport changes size.

Layout required props value. Available props  are - fixed, responsive, fill

fixed: When uses fixed, the image dimensions will not change as the viewport changes (no responsiveness) similar to the native img element. This will not behave like responsive view.

<Image
        layout={fixed}
        src={imgSrc}
        alt="images name"
      />

responsive: When uses responsive, the image will scale the dimensions down for smaller viewports and scale up for larger viewports. Must ensure the parent element is display: block 

<Image
        layout={responsive}
        src={imgSrc}
        alt="images name"
      />

fill: When uses fill, the image will stretch both width and height to the dimensions of the parent element. It provided the parent element is relative. This is usually paired with the objectFit property. Must ensure the parent element position: relative

<Image
        layout={fill}
        src={imgSrc}
        alt="images name"
      />

Finally said that you can use layout={fix} because you want to and <Image /> component like native <img />. layout={fix} behave like img element tag.


Thank you for reading the article. If you face any problem, please comment below.