Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Created December 13, 2018 05:07
Show Gist options
  • Save yano3nora/e506210e7cd5449f4ec8ce526fff6ff8 to your computer and use it in GitHub Desktop.
Save yano3nora/e506210e7cd5449f4ec8ce526fff6ff8 to your computer and use it in GitHub Desktop.
[react: Image onError] Behavior on error of image tag. #react #js
<img
src={this.props.img_url}
alt={this.props.img_alt}
onError={(e) => {
e.target.onerror = null
e.target.src = '/img/error-image.png'
}}
/>
@RafaelLechensqueDeAquino

with typescript is it also possible?

@davi1985
Copy link

This is amazing man.

@AliBakerSartawi
Copy link

AliBakerSartawi commented Dec 1, 2021

This made TypeScript a bit grumpy: TS2339: Property 'src' does not exist on type 'EventTarget'. even though it works fine.

currentTarget will satisfy TS:

e.currentTarget.src = '/img/error-image.png'

@Aaslan01
Copy link

Aaslan01 commented Sep 8, 2022

how can we do this in React Native? am able to do using useState with function, but problem whenever it rerender it change the all the other images

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment