Created
January 14, 2018 19:33
-
-
Save dlebedynskyi/39a18f405fb5de70dffbfab2ee73bc3d to your computer and use it in GitHub Desktop.
Lasy Image Loading
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
class LazyImage extends PureComponent { | |
static defaultProps = { | |
engage: false, | |
}; | |
state = { | |
initialEngage: false, | |
}; | |
componentWillMount() { | |
if (this.props.engage) { | |
this.setState({ initialEngage: true }); | |
} | |
} | |
componentWillReceiveProps(nextProps) { | |
const { engage } = this.props; | |
const { initialEngage } = this.state; | |
if (!engage && nextProps.engage && !initialEngage) { | |
this.setState({ initialEngage: true }); | |
} | |
} | |
render() { | |
const { | |
preview, | |
src, | |
srcSet, | |
media, | |
children, | |
alt, | |
height, | |
width, | |
id, | |
className, | |
webp, | |
webpMedia, | |
} = this.props; | |
const { initialEngage } = this.state; | |
return ( | |
<picture> | |
{webp && | |
initialEngage && ( | |
<source srcSet={webp} media={webpMedia} type="image/webp" /> | |
)} | |
{srcSet && initialEngage && <source srcSet={srcSet} media={media} />} | |
{children && initialEngage && children} | |
<img | |
height={height} | |
width={width} | |
id={id} | |
className={className} | |
alt={alt} | |
srcSet={initialEngage ? srcSet : undefined} | |
sizes={initialEngage ? media : undefined} | |
src={initialEngage ? src : preview} | |
/> | |
</picture> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment