Created
January 10, 2019 21:27
-
-
Save andrzejewsky/247e5faf44bc4898f1dadeea58c14572 to your computer and use it in GitHub Desktop.
ImageResource
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"; | |
class ImageResource extends Component { | |
constructor(props) { | |
super(props); | |
const image = new Image(); | |
image.onload = this.handleLoadImage; | |
this.state = { image, src: props.lowQuality }; | |
} | |
static getDerivedStateFromProps(props, state) { | |
const prevProps = state.prevProps || {}; | |
const isNew = prevProps.original !== props.original; | |
if (isNew) { | |
const original = isNew ? props.original : prevProps.original; | |
const lowQuality = isNew ? props.lowQuality : prevProps.lowQuality; | |
state.image.src = original; | |
return { prevProps: props, src: lowQuality }; | |
} | |
return { prevProps: props }; | |
} | |
handleLoadImage = () => { | |
this.setState({ src: this.props.original }); | |
}; | |
render() { | |
const { width, height, className, alt } = this.props; | |
return ( | |
<img | |
src={this.state.src} | |
width={width} | |
height={height} | |
className={className} | |
alt={alt} | |
/> | |
); | |
} | |
} | |
export default ImageResource; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment