Last active
October 4, 2018 06:57
-
-
Save hartzis/38844d519507a782b29abbd5bf31b55e to your computer and use it in GitHub Desktop.
React Universal/Isomorphic Image onError Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} />; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
complete
andnaturalWidth
solution from here - https://stereochro.me/ideas/detecting-broken-images-js