Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Graceful Image loading in React using react-graceful-image

    Akash GuthaAkash Gutha

    Image loading in react is Error-Prone and has no fallback by default. This issue can be solved using Error Boundaries. However, the one solution is to use an existing library and in this lesson, we are going to look at react-graceful-image and the Image component it provides.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: I have a basic react app set up. This react app has a simple div with the className "App" and it encapsulates an image component. This specific URL loads the image that you're seeing on the right. If you enter the URL wrong, react replaces the image with an error image.

    Ideally, we would like react to fall black to a placeholder image instead of this other image. To fix this issue, we can use the react graceful image package and import the image component from the react graceful image package. Now, we'll simply replace this image with the imported image component.

    Now if you load the page, you can see that it displays a grey square box in the place of the original image, instead of showing that small error icon. The package also allows us to customize the placeholderColor. Let's just give it a slight bluish color. Now if you choose to, you can also omit the placeholder altogether by using this noPlaceholder tag and setting this to true.

    Now, you can see that there is nothing displayed. Let's check this by adding some text below the image component. Now if you reload the page, you can see that the text is the only thing that is being displayed, and there is no image above it. You can also verify this by inspecting the page.

    Let's go into the body. Under the route, you can see that we only have the div with the class App and the text, and you have no traces of the image component. Now if you remove the noPlaceholder altogether, and reference this page, and go into the body, into the route inside the app, you can see that now, we actually have the image component.

    Let's close this. As expected, if you go ahead and make the URL correct, you can see that it loads a character image. You can also add accessibility, using the alternate X property, and you would enter a description that you like, and it will be accessible to the screen readers.