Skip to content

Instantly share code, notes, and snippets.

@mihaiserban
Last active May 17, 2019 09:06
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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