Home > Enterprise >  How to configure 100% image using nextJS <Image />?
How to configure 100% image using nextJS <Image />?

Time:01-09

After upgrade nextJS to the latest version I do get some errors using Image:

// import Image from 'next/image'
<div style={Object.assign({}, styles.slide, style)} key={key}>
  <Image
    src={src}
    alt=""
    width={100   '%'}
    height={100   '%'}
    objectFit="cover"
  />
</div>
  1. 'objectFit' is deprecated
  2. Type 'string' is not assignable to type 'SafeNumber'

Which is the correct way to configure the image as 100% width and height?

CodePudding user response:

I don't know why Nextjs has made it quite hard to use 100% for width and height of an image. A solution which worked for me is this one:

<div style={{ width: "100%", height: "300px", position: "relative" }} >
  <Image src={Your_image} alt="Hero-image" fill />
</div>

This will give you 100% width but you have to adjust height yourself, I guess height: 100% here might also work here but I can't say for sure.

If you wanna change the object-fit for the image, You might have to use a classname or inline-style as ObjectFit prop is deprecated in Next v13 (I suppose it does that on its own now)

<Image src={Your_image} alt="Hero-image" fill style={{ objectFit: "cover" }} />
  • Related