Random UTF-8 characters

Home

31 Aug 2019 in next.jsreactimagesimage fallback

NextJS: Fallback image

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.

const renderImage = (image, fallbackImage) => {
  const onerror = `this.onerror=null;this.src=this.dataset.fallbackImage;`
  return (
    <div dangerouslySetInnerHTML={{
      __html: `<img onError="${onerror}" data-fallback-image=${fallbackImage} src="${image}" />`
    }}>
    </div>
  )
}

I created a small demo of this idea in GitHub: https://github.com/brookslyrette/image-with-fallback

Happy coding!