Skip to content

Instantly share code, notes, and snippets.

@hesoyamcode
Created July 23, 2018 07:14
Show Gist options
  • Save hesoyamcode/222e68157105dbeef96acde9736cdc7c to your computer and use it in GitHub Desktop.
Save hesoyamcode/222e68157105dbeef96acde9736cdc7c to your computer and use it in GitHub Desktop.
Progressive Image with React
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class ProgressiveImage extends Component {
static propTypes = {
preview: PropTypes.string,
image: PropTypes.string
};
state = {
currentImage: this.props.preview,
loading: true
};
componentDidMount() {
this.fetchImage(this.props.image);
}
componentWillReceiveProps(nextProps) {
if (nextProps.image !== this.props.image) {
this.setState({ currentImage: nextProps.preview, loading: true }, () => {
this.fetchImage(nextProps.image);
});
}
}
componentWillUnmount() {
if (this.loadingImage) {
this.loadingImage.onload = null;
}
}
fetchImage = src => {
const image = new Image();
image.onload = () =>
this.setState({ currentImage: this.loadingImage.src, loading: false });
image.src = src;
this.loadingImage = image;
};
style = loading => {
return {};
};
render() {
const { currentImage, loading } = this.state;
const style = {
backgroundImage: `url(${currentImage})`,
transition: '0.5s filter linear',
filter: `${loading ? 'blur(50px)' : ''}`,
width: '100%',
height: '100%',
backgroundSize: 'contain',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center'
};
return <div style={{ ...style }} />;
}
}
export default ProgressiveImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment