Skip to content

Instantly share code, notes, and snippets.

@smddzcy
Created November 1, 2018 10:31
Show Gist options
  • Save smddzcy/010c9e1bd648920d524a5e79a4b43612 to your computer and use it in GitHub Desktop.
Save smddzcy/010c9e1bd648920d524a5e79a4b43612 to your computer and use it in GitHub Desktop.
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Loading from '../Loading';
export default class Image extends PureComponent {
static loadedSrcs = new Set();
constructor(props, context) {
super(props, context);
this.state = { isLoaded: false, isLoading: false, error: null };
this.loadImage = this.loadImage.bind(this);
this.imgOnload = this.imgOnload.bind(this);
this.imgOnerror = this.imgOnerror.bind(this);
}
componentWillMount() {
this.loadImage();
}
componentWillReceiveProps(nextProps) {
if (nextProps.src !== this.props.src) {
this.loadImage();
}
}
imgOnload() {
this.setState({ isLoading: false, isLoaded: true, error: null });
Image.loadedSrcs.add(this.props.src);
}
imgOnerror(err) {
this.setState({ isLoading: false, isLoaded: false, error: err });
}
loadImage() {
if (Image.loadedSrcs.has(this.props.src)) {
return this.setState({ isLoading: false, isLoaded: true, error: null });
}
this.setState({ isLoaded: false, isLoading: true, error: null });
const image = new window.Image();
image.src = this.props.src;
image.onload = this.imgOnload;
image.onerror = this.imgOnerror;
}
render() {
const { isLoaded, isLoading, error } = this.state;
const { loadingProps, ...imgProps } = this.props;
if (error) return <i className="fa fa-warning fa-2x" />;
if (!isLoaded) {
if (!isLoading) return null;
return <Loading isGold {...loadingProps} />;
}
return <img alt="" {...imgProps} />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment