Handling image loading and error state in Next.js
A guide on how to use placeholder and onError props in Next.js
November 17th, 2021
November 17th, 2021
TL;DR
Check the full code here
next/image
provides an easy way to create an image.
However, we still need to configure some properties to cater to our specific needs, such as:
The GIF below shows what a user will see for an image loaded using a slow internet connection.
It gives the impression that something is wrong with our app.
Simply adding the placeholder
and blurDataURL
will do the trick.
The code will yield the following result:
There's a brief delay before the placeholder is loaded because even the placeholder image is needed to be fetched from the server.
If we need to make sure that there's an immediate placeholder to the image, refer to this guide on how to create a dynamic image placeholder
The good thing is that once the placeholder image is loaded, all other images that use the same asset will display the placeholder immediately.
One possibility is that the user will stare at the placeholder for eternity.
Or this sadder version which shows the alt
and much space.
It is not fun to see too much unnecessary space, is it?
We can replace the value of src
with the path to error image
in the onError
callback when an error happens.
I believe it's much better.
To make the behavior easy to replicate, we can create a custom image component.
When a web application displays many images, it is a good idea to give immediate feedback to the user of what is happening. One way to address this is to use an alternate image to show the current state of an image.