0

I'm trying to get the image sizes from a URL in my Next.js app so I can use the NextJs Image component. I'm fetching the images from a Headless CMS that only returns the urlm so I was trying to do something like:

const BuilderImage = ({ src, alt }) => {
  const [imageDimensions, setImageDimensions] = useState({ width: 1024, height: 500 });
  
  const img = new Image();

  useEffect(() => {
    img.src = src;

    img.onload = () => {
      setImageDimensions({
        height: img.height,
        width: img.width
      });
    };
  }, []);

  return (
    <Image
      src={src}
      width={imageDimensions.width}
      height={imageDimensions.height}
      alt={alt}
      objectFit="cover"
    />
  );
};

But it isn't working. My error:

TypeError: Cannot destructure property 'src' of '_param' as it is undefined.

Does anybody knows what's going on? thanks

Emiliano
  • 437
  • 1
  • 4
  • 14
  • why you don`t used layout="responsive" ? – H9ee Apr 29 '22 at 17:14
  • Does this answer your question? [How to use Image component in Next.js with unknown width and height](https://stackoverflow.com/questions/66353475/how-to-use-image-component-in-next-js-with-unknown-width-and-height) – Andrew Hulterstrom Apr 29 '22 at 19:37

0 Answers0