NextjS Image issue with src and default external image URL

Viewed 5076

I am using the latest version of NextJS 10.0.9. I've got an Image that I'm trying to display, however I'm receiving the error:

Error: Image with src "https://picsum.photos/480/270" must use "width" and "height" properties or "layout='fill'" property.

As you can see here though, I do have all of those properties set:

<div className="card-img">
  <Image
    alt={media?.title}
    title={media?.title}
    src={media?.previewImage || 'https://picsum.photos/480/270'}
    width={480}
    height={270}
    layout="fill"
  />
</div>

For some reason, it appears that having a default external image doesn't want to play nicely with the Image component. Does anyone know a workaround or reason why this might be the case?

A little side note too: I've got a Typescript error on the layout property that says "Type '"fill"' is not assignable to type '"fixed" | "intrinsic" | "responsive" | undefined'.". I'm not sure if that's related?

1 Answers

If you use layout='fill', you do not need a width and height attribute. The error message isn't completely clear, but that "or" is an exclusive or. You can define the width/height or layout='fill', but not both.

This is a byproduct of how next/image works: the width/height props are used to determine aspect ratio, not necessarily display size.

Since layout='fill' means "stretch to fill the parent element", the width and height are meaningless. So to fix the error, either remove layout='fill', or remove the dimensions.


You've probably already seen this, but here are the docs just in case: https://nextjs.org/docs/api-reference/next/image

Related