ccurtin
7/27/2017 - 1:13 PM

Image Preloader for React Apps - the LoadingAnimation01 can be any loading icon/CSS...

Image Preloader for React Apps - the LoadingAnimation01 can be any loading icon/CSS...

import React from 'react';
import LoadingAnimation01 from './LoadingAnimation01'

class ImgPreloader extends React.Component {
  constructor(props) {
    super(props);
    this.state = { imageStatus: 'loading', imageLoaded: false };
  }

  componentDidMount() {
    /*
      FOR BUG FIX:
      @link [ https://bugs.chromium.org/p/chromium/issues/detail?id=7731 ]
      preventative measure! W/O the preloader will sometimes never fire off the `onLoad()` method.
    */
    var img = new Image()
    img.src = this.props.srcLink
    this.imageRef.src = img.src
  }

  handleImageLoaded(e) {
    this.setState({ imageStatus: 'loaded', imageLoaded: true });
  }

  handleImageErrored() {
    this.setState({ imageStatus: 'failed to load', imageLoaded: false });
  }

  render() {
    return (
        <div className={this.props.className ? this.props.className : ""} >
            <img
              ref={(input) => this.imageRef = input}
              alt={this.props.altText ? this.props.altText : ""}
              data-loaded={this.state.imageLoaded ? "loaded" : "not-loaded"}
              onLoad={this.props.onLoadDo ? this.props.onLoadDo.bind(this, this) : this.handleImageLoaded.bind(this)}
              onError={this.handleImageErrored.bind(this)}
              src={this.props.srcLink}
              />
            {this.state.imageLoaded && this.props.srcLink !== null ? (this.props.children) : (<LoadingAnimation01 />)}
        </div>
    )
  }
}
export default ImgPreloader;