DEV Community

Diogo Capela
Diogo Capela

Posted on • Edited on • Originally published at diogocapela.com

Adding fallback images onto your React projects

If you are developing a web application, then there are a lot of things to consider. One important aspect is the images that are used, for aesthetic purposes or various other reasons (e.g. icons). Either way, it is important to have a backup plan in case images don't load for some reason.

For example, if you are pulling image data from an external database or API, sometimes you can't be 100% sure that it will return you an existing image file. In those cases, you may end up with a broken image icon on your webpage, and depending on the browser, there may be no indication at all that something went wrong. Frontend developers should predict these cases and adequately provide a fallback image when it happens.

To achieve this we can use the onerror event handler on img elements. This handle will get called if an error occurs while loading or rendering an image. According to MDN Web Docs, it can happen in several situations, including:

  • The src attribute is empty or null.
  • The src URL is the same as the URL of the page the user is currently on.
  • The image is corrupted in some way that prevents it from being loaded.
  • The image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the img element's attributes.
  • The image is in a format not supported by the user agent.

To do this with React we just need to use onError instead (the SyntheticEvent wrapper from React’s event system).

import React from 'react';

export default function App() {
  const addImageFallback = (event) => {
    event.currentTarget.src = '/images/fallback.png';
  };

  return (
    <img src="/images/broken.png" alt="" onError={addImageFallback} />
  );
}
Enter fullscreen mode Exit fullscreen mode

If using TypeScript, we just need to properly type the event parameter of the addImageFallback function.

import React, { SyntheticEvent } from 'react';

export default function App() {
  const addImageFallback = (event: SyntheticEvent<HTMLImageElement, Event>) => {
    event.currentTarget.src = '/images/fallback.png';
  };

  return (
    <img src="/images/broken.png" alt="" onError={addImageFallback} />
  );
}
Enter fullscreen mode Exit fullscreen mode

And that's it! Now you know how to add fallback images to your React projects. Hopefully, this has been a valuable resource if you are just starting your coding journey.

Top comments (0)