Home > Software engineering >  How to convert <img> element to Nextjs <Image> component
How to convert <img> element to Nextjs <Image> component

Time:12-14

I've been writing Nextjs for a while but some of the image components are still in <img> tag like this. (based on TailwindCSS)

    <div className="relative">
                        <div className="absolute inset-0 flex flex-col" aria-hidden="true">
                            <div className="flex-1 bg-transparent" />
                            <div className="w-full flex-1 bg-black" />
                        </div>
                        <div className="mx-auto max-w-7xl px-4 sm:px-6">
                            <img
                                className="relative rounded-lg"
                                src="/images/somephoto.png"
                                alt="screenshot"
                            />
                        </div>
                    </div>

The current code shows the image in the center of the page with a relative position. I've tried to convert the tag into the Next <Image /> component though it is hard to keep the styling since we need to specify width and height.

I would like to know the conversion tips between <img> and Next <Image> if any. (Appreciate it if you have an idea for the above case example)

CodePudding user response:

As your current code is working correctly without adding any additional staying to the img tag, you can just replace it with the <Image /> component from next.js

<div className="relative">
  <div className="absolute inset-0 flex flex-col" aria-hidden="true">
    <div className="flex-1 bg-transparent" />
    <div className="w-full flex-1 bg-black" />
  </div>
  <div className="mx-auto max-w-7xl px-4 sm:px-6">
    <Image
      loader={myLoader}
      src="me.png"
      alt="Picture of the author"
      layout='fill'
    />
  </div>
</div>;
  • Related