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