Skip to content

Instantly share code, notes, and snippets.

@perjansson
Last active June 14, 2020 08:20
Show Gist options
  • Save perjansson/dfca1e1438703137bf1068f157d54a2d to your computer and use it in GitHub Desktop.
Save perjansson/dfca1e1438703137bf1068f157d54a2d to your computer and use it in GitHub Desktop.
class ProgressiveImage extends Component {
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 {
transition: '0.5s filter linear',
filter: `${loading ? 'blur(50px)' : ''}`,
}
}
render() {
const { currentImage, loading } = this.state
const { alt } = this.props
return <img style={this.style(loading)} src={currentImage} alt={alt} />
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment