Home > Mobile >  Can Dynamic and Constantly changing image URL work with Next/image
Can Dynamic and Constantly changing image URL work with Next/image

Time:07-07

Can Next/Image use empty string variables for the src that'd get set later via an API?

I have an image url that I'd retrieve from an API. so the image src gets set after runtime. By default it's an empty string '' and then using SWR later it gets set to the full image url, eg https://i.imgur.com/Thgw1b.png

However, I get a build time error, Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} despite having src already set. The same error occurs if src='' as well.

const myComponent = ({imageURL = ''}) => {
  // imageURL starts off as '', then the parent updates that value to a proper image url when the API returns a url value. 

  return (
    <>
      // TODO: Fix build time error saying no src is set, despite being set to '' initially
      <Image src={imageURL} alt='Dynamic Image' layout='responsive'/>
    </>
  );
}

Can Next/Image src images be set fully dynamically? Where it starts as an empty string then the src url gets populated later?

I've seen some answers suggesting useServerSide Props, but that won't work in my use case as the image url API gives a different image url every X hours (Hence using SWR). So just loading in once doesn't work.

Note that using <img> tags works perfectly. Initially there's no image, then after the image url gets set to the variable, the img tag loads the image in.

CodePudding user response:

Try rendering the Image conditionally like so :

return (
    <>
      {imageUrl &&
        <Image src={imageURL} alt='Dynamic Image' layout='responsive'/>
      }
    </>
)
  • Related