Skip to content

Instantly share code, notes, and snippets.

@mihaiserban
Last active May 17, 2019 09:06
Show Gist options
  • Save mihaiserban/751a84df361178db387e130d0c07693e to your computer and use it in GitHub Desktop.
Save mihaiserban/751a84df361178db387e130d0c07693e to your computer and use it in GitHub Desktop.
React image fallback - in case src fails try to load a placeholder instead
import React from "react";
import PropTypes from "prop-types";
class Image extends React.Component {
constructor(props) {
super(props);
this.state = { src: props.src };
}
componentWillReceiveProps(nextProps) {
if (this.props.src !== nextProps.src) {
this.setState({
src: props.src
});
}
}
handleImageLoad() {
console.log("image loaded", this.state.src);
}
handleImageError() {
console.log("image failed loaded", this.state.src);
if (this.props.placeholder) {
console.log("try load placeholder");
this.setState({ src: this.props.placeholder });
}
}
handleOnContextMenu(e) {
console.log("handleOnContextMenu");
if (this.props.disableContextMenu) {
e.preventDefault();
}
}
render() {
const { src, placeholder, disableContextMenu, ...other } = this.props; // es7
return (
<img
src={this.state.src}
onLoad={this.handleImageLoad.bind(this)}
onError={this.handleImageError.bind(this)}
{...other}
onContextMenu={this.handleOnContextMenu.bind(this)}
/>
);
}
}
Image.defaultProps = {
src: "",
placeholder: "",
disableContextMenu: false
};
Image.propTypes = {
src: PropTypes.string.isRequired,
placeholder: PropTypes.string,
disableContextMenu: PropTypes.bool
};
export default Image;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment