Next.js Discord

Discord Forum

Image Loading Issue in AspectRatio Component

Unanswered
Highlander posted this in #help-forum
Open in Discord
HighlanderOP
I need help resolving an issue with image loading in an AspectRatio component. I’d like the image to load and position instantly within the component, without any visible delay or layout shift.

I’m including the current code below for context:
<AspectRatio ratio={4 / 3}> <Image src={variant.images[0].url} alt={variant.fullName} sizes="(min-width: 1024px) 20vw, (min-width: 768px) 25vw, (min-width: 640px) 33vw, (min-width: 475px) 50vw, 100vw" objectFit="contain" fill /> </AspectRatio>

3 Replies

This will not be possible with the current implementation, images are lazy loaded so image will load slightly later and need to adjust it's position after being loaded to fill the parent.

I suggest creating an <ImageLoader /> component (can be a spinner or anything), then showing that until the image is fully loaded then show the image.

You can do this very easily using the onLoad property on next/image
In every project, I always create a wrapper component around next/image to handle loading smoothly.

In the screenshot below you can see that I initially show the <ImageLoader /> component on top while the actual image is loading in the background until the onLoad event from next/image updates state to hide the <ImageLoader /> and smoothly fading in to replace the loader.
Don't worry about the fallbackLoader and onError props in this case, I have those setup in case image optimization fails, I fallback to another provider.