1

Is it better to use 'next/image' instead of normal img tag. if it is why?

I want to show an image but I'm giving width and height in styles. like this... <img className="img" src='url/img.png'/>

class img gives auto width and height in rem. I can't use next/img tag because I have to give width in pixels and can't give 'auto'. Is there a workaround for this.

I can wrap img tag with a div with 'img' classname and give layout='fill' like this.

import Image from 'next/image';
<div className='img'>
<Image layout='fill' src="lll.jpg"/>
</div>

but I feel this unnecessary. I would like to know your ideas?

Pavel Fedotov
  • 748
  • 1
  • 7
  • 29
Shehan DMG
  • 141
  • 1
  • 15

1 Answers1

1

Is it better to use 'next/image' instead of normal img tag. if it is why?

Yes, it is better to use the next/image over the standard HTML img tag, because of its automatic optimization mechanism, next/image will load your images in the most efficient way possible using lazy load, WebP format and using responsiveness, it will also take care of many SEO aspects for you like Layout Cumulative Layout Shift.

Feel free to check this answer for more details: https://stackoverflow.com/a/67886607/14900930

As for your problem, If you don't want to specify width and height properties (which only supports pixel unit) directly to the next/image component your only option is to use layout="fill" with a position:relative for the parent as mentioned in their docs.

When fill, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative.
This is usually paired with the objectFit property.
Ensure the parent element has position: relative in their stylesheet.

So for your approach, it is fine because it is necessary to have a parent for a next/image component with a layout='fill' property, just make sure it has a position relative.

I would also suggest using the sizes property to ensure the correct images are served for each device, Feel free to check their docs

Zakaria Benali
  • 298
  • 2
  • 5