Unable to load image in Reactjs

Viewed 45

I am working with Reactjs(Nextjs framework),I am trying to display image in page but right not showing,I do not want to use "height" and "width" attribute in Image tag,I tried with following code but image is not showing

<Image src="/../public/img/services-02.jpg" className="card-img" alt="Card image" layout="fill"/>

I tried with following code also,image is displaying but i do not want to use "Height" and "width"

<Image src="/../public/img/services-02.jpg" className="card-img" alt="Card image" width={50}
        height={50}/>
2 Answers

Why you don't want to use width and height? In Next.JS there are used to set original size and ratio. After that you can do whatever with size in css.

https://nextjs.org/docs/api-reference/next/image#width

As you can see in docs width and height can means both rendered or original size, depend on what layout and size you choosed

If I get it right that solution gives you pros such as:

  • Always having width and height is good for SEO
  • Nobody Can put 4000x4000 image unnecessary

If the requirement is not to use width and height, with Next-Image, something like below works.

<div style={{width: '100%', height: '100%', position:'relative'}}>
  <Image
    alt='Image description'
    src='image.jpg'
    layout='fill'
    objectFit='contain'
  />
</div>

You can pick the required value for the layout field, based on your requirement. Please check: https://nextjs.org/docs/api-reference/next/image#layout

Let me know whether this works for you.

Related