Skip to content

Instantly share code, notes, and snippets.

@hartzis
Last active October 4, 2018 06:57
Show Gist options
  • Save hartzis/38844d519507a782b29abbd5bf31b55e to your computer and use it in GitHub Desktop.
Save hartzis/38844d519507a782b29abbd5bf31b55e to your computer and use it in GitHub Desktop.
React Universal/Isomorphic Image onError Component
class Image extends Component {
componentDidMount() {
// if image hasn't completed loading, then let react handle error
if (!this._image.complete) return;
// if image has finished loading and has 'errored'(errored when naturalWidth === 0)
// then run the onError callback
if (this._image.naturalWidth === 0) {
this.props.onError();
}
}
render() {
const {imageSrc, onError} = this.props;
return <img ref={(r)=>this._image = r} src={imageSrc} onError={onError} />;
}
}
@hartzis
Copy link
Author

hartzis commented Jul 14, 2016

complete and naturalWidth solution from here - https://stereochro.me/ideas/detecting-broken-images-js

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