2017-05-31 15:07:25 +00:00
|
|
|
import React from 'react';
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
|
|
|
|
class ImageLoader extends React.PureComponent {
|
|
|
|
|
|
|
|
static propTypes = {
|
2017-06-15 12:10:41 +00:00
|
|
|
alt: PropTypes.string,
|
2017-05-31 15:07:25 +00:00
|
|
|
src: PropTypes.string.isRequired,
|
2017-06-06 17:30:17 +00:00
|
|
|
previewSrc: PropTypes.string.isRequired,
|
|
|
|
width: PropTypes.number.isRequired,
|
|
|
|
height: PropTypes.number.isRequired,
|
2017-05-31 15:07:25 +00:00
|
|
|
}
|
|
|
|
|
2017-06-15 12:10:41 +00:00
|
|
|
static defaultProps = {
|
|
|
|
alt: '',
|
|
|
|
};
|
|
|
|
|
2017-05-31 15:07:25 +00:00
|
|
|
state = {
|
|
|
|
loading: true,
|
|
|
|
error: false,
|
|
|
|
}
|
|
|
|
|
|
|
|
componentWillMount() {
|
2017-06-06 17:30:17 +00:00
|
|
|
this._loadImage(this.props.src);
|
2017-05-31 15:07:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
componentWillReceiveProps(props) {
|
2017-06-06 17:30:17 +00:00
|
|
|
this._loadImage(props.src);
|
2017-05-31 15:07:25 +00:00
|
|
|
}
|
|
|
|
|
2017-06-06 17:30:17 +00:00
|
|
|
_loadImage(src) {
|
2017-05-31 15:07:25 +00:00
|
|
|
const image = new Image();
|
2017-06-06 17:30:17 +00:00
|
|
|
|
2017-06-01 15:25:10 +00:00
|
|
|
image.onerror = () => this.setState({ loading: false, error: true });
|
2017-06-06 17:30:17 +00:00
|
|
|
image.onload = () => this.setState({ loading: false, error: false });
|
|
|
|
|
2017-05-31 15:07:25 +00:00
|
|
|
image.src = src;
|
2017-06-06 17:30:17 +00:00
|
|
|
|
2017-06-01 15:25:10 +00:00
|
|
|
this.setState({ loading: true });
|
2017-05-31 15:07:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
2017-06-15 12:10:41 +00:00
|
|
|
const { alt, src, previewSrc, width, height } = this.props;
|
2017-05-31 15:07:25 +00:00
|
|
|
const { loading, error } = this.state;
|
|
|
|
|
2017-06-06 17:30:17 +00:00
|
|
|
return (
|
|
|
|
<div className='image-loader'>
|
2017-06-15 12:10:41 +00:00
|
|
|
<img
|
|
|
|
alt={alt}
|
2017-06-06 17:30:17 +00:00
|
|
|
className='image-loader__img'
|
|
|
|
src={src}
|
|
|
|
width={width}
|
|
|
|
height={height}
|
|
|
|
/>
|
|
|
|
|
|
|
|
{loading &&
|
2017-06-15 12:10:41 +00:00
|
|
|
<img
|
|
|
|
alt=''
|
2017-06-06 17:30:17 +00:00
|
|
|
src={previewSrc}
|
|
|
|
className='image-loader__preview-img'
|
|
|
|
/>
|
|
|
|
}
|
|
|
|
</div>
|
|
|
|
);
|
2017-05-31 15:07:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export default ImageLoader;
|