Image fallback for Broken images — React/React Native

Md Moin
2 min readDec 31, 2018

--

Few days back i had a story on resolution to broken image links using angular, today here i’m with the solution to the same problem in react & react native. If you have missed out on how we achieved this in angular you can refer the below link

Just a quick run through on how we fix this problem, as per the HTML standards every image tag comes with an error event which gets triggered in case of any broken image links. I have written a component in react native to render fallback images, but the same thing will apply even in react except for the fact that instead of using Image component of react-native you can use img tag of html in react applications.

So what have we dont here, we have a state with default fallback image & the component receives the prop src which updates the state on load, i didnt need to check for prop updates since it helps only in rendering the image & its fallback.

The onError event is the one being tracked here as soon as it fires for broken images we load the fallback image.

You can use the component as <ProductImage src={some_image_url}/>

Image fallback react/react native component

You can see the left image loads a fallback image incase of broken links, where as the right one is the actual scenario of when an image is unavailable.

--

--

Md Moin
Md Moin

Written by Md Moin

I’m a dev who codes for fun & likes to share my learnings.

No responses yet