Graceful Image loading in React using react-graceful-image

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.

You must be a Member to view code

Instructor: 00:00 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.

00:19 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.

00:38 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.

01:06 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.

01:24 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.

01:48 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.