Understand Image Loading Errors
Learn about the <img /> , what causes image loading errors, and what options we have to solve this.
Our component handles optional props and renders our fallback image, but there’s one thing missing: what happens if the provided image fails to load? Possibly an edge case but definitely something we should handle.
First, let’s review the reasons why images fail to load by taking a look at the MDN docs.
go through reasons
If you notice, the onerrorevent is called when any one of these happens.
That means we can define our own error handler function and cause a side effect. Awesome! We have a plan.
Resources
The following resources provide more information for this lesson:
- MDN docs <img />: Image loading errors
- Check if img src is valid using JavaScript
- r/reactjs: How to check image exists
Transcript
In the last video we implemented a fallback avatar URL and a fallback alt text. This is great, in that it allows us to make our properties both URL and alt optional, but there's one thing that's missing.
What happens if the provided image fails to load, or somebody passes a URL that's an empty string, another reason that it would fail to load? Possibly an edge case, but definitely something we should handle.
One thing I want us to look at is, over on MDN, talk about image loading errors and what happens when an error occurs. Here, we can see if an error occurs while loading or rendering an image, and an onerror event handler has been set on the error event, that will get called.
Some examples where this could happen. Empty string, which again, because in TypeScript we've set the property as a string, this could happen. Null wouldn't happen necessarily, but empty string could. Another, which is the image is corrupted in some way that prevents it from being loaded. Maybe it moved, or maybe it's the wrong URL.
Now if we go back to our IDE, one thing we can do is define an onError handler. I like to add some notes here. What we can do is, if onError is called, meaning an image loading error, then use fallback URL and alt text. We'll probably need to useState. What we'll do is update src and alt when onError is called.
It should be pretty simple to implement. We'll do that in the next video.