Skip to content

Instantly share code, notes, and snippets.

@glarivie
Last active February 7, 2018 15:18
Show Gist options
  • Save glarivie/419c1b6a3ed9c71a5b55f51558307c53 to your computer and use it in GitHub Desktop.
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)
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