Front-End Insights

[NNM #3] React Image Fallback – handling missing images


I think that the last day of the month is the best moment to publish the next post of my “Node Module of the Month” series. Today I will show you a React Image Fallback module. As the name of this small module suggests, it allows us to show a fallback image in a situation when the real image is missing. The name also contains the word “React”. This implies that it is a React component. Let’s take a look at how can we utilise it.

How to install and use the React Image Fallback module

As it is a regular NPM module, we can install it in the normal way:

npm install --save-dev react-image-fallback

Now that we have the module installed, let’s take a quick look at a sample usage (from the README file of the project):

import React From "react";
import ReactImageFallback from "react-image-fallback";

export default class ShowImage extends React.Component {
  render() {
    return (
        <ReactImageFallback src="my-image.png" 
                            alt="cool image should be here" 
                            className="my-image" />

As you can see, we can easily add the React Image Fallback component using import. We can then just use it in the JSX.

Required props

The component takes several pieces of information as props. Two of them are required: src and fallbackImage. The src props is for setting the path to the image we want to show. This value will be assigned to the src attribute of the resulting img element. fallbackImage tells the component what image should be shown in a situation when the src image is missing.

Not required props

Apart from the src and fallbackImage attributes we can set additional props which are not required. The most important one is initialImage. By setting this attribute, we can tell the component what image should be shown before the main or fallback image is finally shown. You can usually use it to show a “loader” or something.

Other not required props are onLoad and onError – they are actually callbacks. The first one is called if the initial image loads successfully. The second one is called if the initial image load fails.

Additionally we can, of course, pass any other props available for the img element such as alt or className.


I, personally, have used this component in my recent React projects and have found it very useful. I can imagine plenty of situations when we are unsure that the image will exist. Instead of showing the image conditionally, we can use the React Image Fallback component. For example we can show a generic “no image found” image instead of the missing one. I hope this will be useful for you too.

P.S. More information about the presented module can be found in its GitHub repository.

  • Dendi Sunardi

    How about setup the transition/animation between initial image and src image ?