Skip to content

Instantly share code, notes, and snippets.

@mihaiserban

mihaiserban/image-react.js

Last active May 17, 2019
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