Created
July 23, 2018 07:14
-
-
Save hesoyamcode/222e68157105dbeef96acde9736cdc7c to your computer and use it in GitHub Desktop.
Progressive Image with React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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