NextJS: Fallback image
Broonix
August 31, 2019
Quick post on a problem I recently had to solve. I was looking to have an image tag fallback to a different image if the image set in the src property doesn't load.
Now normally you can handle this all on the client side using the image tags onError listener. There is a bit of a trick to get this idea to work with NextJS. The onError event may not be fired when rendering via SSR. This is because the image content may load before ReactDOM has completed hydration.
Once simple way to work around this issue is to force this to happen after ReactDOM has completed hydration. This can be accomplished by forcing the fallback to always happen on the client side.
[Code block (js)]
I created a small demo of this idea in GitHub: https://github.com/brookslyrette/image-with-fallback
Happy coding!
Read the original post with all embeds and interactive content at https://rants.broonix.ca/nextjs-fallback-image/
Discussion in the ATmosphere