How to Hide a Broken Image in React?

In React, you can use the an onError (or onLoad) event handler on the image to either hide the image or reset the image src attribute. In either case, it will hide the broken image icon shown by the browser when an image fails to load.

#Hiding the Broken Image in DOM

You can simply set the image to not show when it fails to load, for example, like so:

<img src="image.png" onError={(event) => event.target.style.display = 'none'} />

You could also style it to be hidden by default, and show it onLoad like so:

<img src="image.png" onLoad={(event) => event.target.style.display = 'inline-block'} />

If you just want to hide the broken image icon whilst still having the space for the image reserved on the page, you could set the opacity or visibility properties instead of display.

#Resetting the Broken Image src Attribute

You may reset the src attribute to an empty string like so:

<img src="image.png" onError={(event) => event.target.src = ''} />

Alternatively, you may remove the src attribute altogether like so:

<img src="my/image.png" onError={(event) => event.target.removeAttribute('src')} />

Please note that these won't work if the image has an alt attribute. In such cases, as expected, the value of the alt attribute will display (and depending on the browser you're using, a broken image icon might appear as well). If you need a workaround for that, then you can perhaps specify a default / fallback image in case of an error.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.