Last active
March 19, 2019 16:13
-
-
Save dane-stevens/5fc2352b4b678bd9e7026dc483669186 to your computer and use it in GitHub Desktop.
This file contains 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 Img extends React.Component { | |
constructor(props) { | |
... | |
this.state = { | |
... | |
fullsizeLoaded: false | |
} | |
... | |
} | |
... | |
render() { | |
// Destructure props and state | |
... | |
const { isInViewport, width, fullsizeLoaded } = this.state | |
... | |
// Modify the queryString for the LQIP image: replace the width param with a value 1/10 the fullsize | |
const lqipQueryString = queryString.replace(`w=${ width }`, `w=${ Math.round(width * 0.1) }`) | |
// Set the default styles. The full size image should be absolutely positioned within the <figure /> element | |
const styles = { | |
figure: { | |
position: 'relative', | |
margin: 0 | |
}, | |
lqip: { | |
width: '100%', | |
filter: 'blur(5px)', | |
opacity: 1, | |
transition: 'all 0.5s ease-in' | |
}, | |
fullsize: { | |
position: 'absolute', | |
top: '0px', | |
left: '0px', | |
transition: 'all 0.5s ease-in' | |
} | |
} | |
// When the fullsize image is loaded, fade out the LQIP | |
if (fullsizeLoaded) { | |
styles.lqip.opacity = 0 | |
} | |
return( | |
<figure | |
style={ styles.figure } | |
... | |
> | |
{ | |
isInViewport && width > 0 ? ( | |
<React.Fragment> | |
{/* Load fullsize image in background */} | |
<img | |
onLoad={ () => { this.setState({ fullsizeLoaded: true }) } } | |
style={ styles.fullsize } | |
src={`https://cdn.tueri.io/${ src }/${ kebabCase(alt) }.${ ext }${ queryString }`} | |
alt={ alt } | |
/> | |
{/* Load LQIP in foreground */} | |
<img | |
onLoad={ () => { this.setState({ lqipLoaded: true }) } } | |
style={ styles.lqip } | |
src={`https://cdn.tueri.io/${ src }/${ kebabCase(alt) }.${ ext }${ lqipQueryString }`} | |
alt={ alt } | |
/> | |
</React.Fragment> | |
) : null | |
} | |
</figure> | |
) | |
} | |
} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment