2017-05-31 15:07:25 +00:00
|
|
|
import React from 'react';
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
|
|
|
|
class ImageLoader extends React.PureComponent {
|
|
|
|
|
|
|
|
static propTypes = {
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
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-06 17:30:17 +00:00
|
|
|
const { 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'>
|
|
|
|
<img // eslint-disable-line jsx-a11y/img-has-alt
|
|
|
|
className='image-loader__img'
|
|
|
|
src={src}
|
|
|
|
width={width}
|
|
|
|
height={height}
|
|
|
|
/>
|
|
|
|
|
|
|
|
{loading &&
|
|
|
|
<img // eslint-disable-line jsx-a11y/img-has-alt
|
|
|
|
src={previewSrc}
|
|
|
|
className='image-loader__preview-img'
|
|
|
|
/>
|
|
|
|
}
|
|
|
|
</div>
|
|
|
|
);
|
2017-05-31 15:07:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export default ImageLoader;
|