Skip to content

Instantly share code, notes, and snippets.

@ccurtin
Created July 27, 2017 13:13
Show Gist options
  • Save ccurtin/abce9e3ee489ab1fb9c7308ff414602d to your computer and use it in GitHub Desktop.
Save ccurtin/abce9e3ee489ab1fb9c7308ff414602d to your computer and use it in GitHub Desktop.
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment