I would like to explain here how I include images in my React projects.
It's very common to use the img
tag directly everywhere like this <img src="my-image.png" />
but as this is not a React component we can't apply some layer on it then I prefer to have an Image component in my apps.
In this Image component one case that I usually handle is when the image fails to load, this can happen when the user internet connection is flaky or even if the image is not available anymore, maybe the owner of the image just deleted it.
By default, the browser will display a broken image icon or something bad for the user and we don't want that. So we can use the onError
property of img
to trigger a state change then we can provide a different image URL that we can trust. Check the Image component code.
Then when the user's connection fails the browser will not show a broken image icon if we provide a better fallback when using this Image component, for instance, in a PersonImage component that displays the user profile picture in our app.
I believe you are thinking: how the browser is going to load the fallback image anyway if the connection is failing? Well, we can add in our HTML head section a preload link to load our fallback image in advance:
That is it, simple and straightforward. Are you doing something like this in our React apps? Did you know about onError
property already? Leave a comment 😉
Top comments (1)
Hah) thank you, it helps me)