Last active
February 7, 2018 15:18
-
-
Save glarivie/419c1b6a3ed9c71a5b55f51558307c53 to your computer and use it in GitHub Desktop.
Hide <img /> on error with React (how to hide default browser broken image icon on React)
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
import React, { PureComponent } from 'react' | |
import PropTypes from 'prop-types' | |
class Image extends PureComponent { | |
static propTypes = { | |
disabled: PropTypes.bool, | |
} | |
static defaultProps = { | |
disabled: true, | |
} | |
state = { disabled: this.props.disabled } | |
_hideImage = () => this.setState({ disabled: true }) | |
_displayImage = () => this.setState({ disabled: false }) | |
render = () => { | |
const { disabled } = this.state | |
if (disabled) | |
return false | |
return ( | |
<img | |
onError={this._hideImage} | |
onLoad={this._displayImage} | |
{...this.props} | |
/> | |
) | |
} | |
} | |
export default Image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment