The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

46 lines
1010 B

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. class ImageLoader extends React.PureComponent {
  4. static propTypes = {
  5. src: PropTypes.string.isRequired,
  6. }
  7. state = {
  8. loading: true,
  9. error: false,
  10. }
  11. componentWillMount() {
  12. this.loadImage(this.props.src);
  13. }
  14. componentWillReceiveProps(props) {
  15. this.loadImage(props.src);
  16. }
  17. loadImage(src) {
  18. const image = new Image();
  19. image.onerror = () => this.setState({ loading: false, error: true });
  20. image.onload = () => this.setState({ loading: false, error: false });
  21. image.src = src;
  22. this.lastSrc = src;
  23. this.setState({ loading: true });
  24. }
  25. render() {
  26. const { src } = this.props;
  27. const { loading, error } = this.state;
  28. // TODO: handle image error state
  29. const imageClass = `image-loader__img ${loading ? 'image-loader__img-loading' : ''}`;
  30. return <img className={imageClass} src={src} />; // eslint-disable-line jsx-a11y/img-has-alt
  31. }
  32. }
  33. export default ImageLoader;