Created
February 9, 2020 19:44
-
-
Save sambeevors/c096b96e3b0efe2c60b6c20a53213e77 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
import 'intersection-observer' | |
import { useState } from 'react' | |
import { useInView } from 'react-intersection-observer' | |
const Image = ({ src, alt = '', width, height, style = {}, ...props }) => { | |
const [ref, inView] = useInView({ | |
threshold: 0, | |
triggerOnce: true | |
}) | |
const [isLoaded, setIsLoaded] = useState(false) | |
return ( | |
<div | |
ref={ref} | |
style={{ | |
position: 'relative', | |
paddingTop: `${(height / width) * 100}%`, | |
...style | |
}} | |
{...props} | |
> | |
<img | |
src={inView ? src : undefined} | |
alt={alt} | |
style={{ | |
position: 'absolute', | |
top: 0, | |
left: 0, | |
width: '100%', | |
height: '100%', | |
opacity: isLoaded ? 1 : 0, | |
transition: 'opacity 0.3s' | |
}} | |
onLoad={() => setIsLoaded(true)} | |
/> | |
</div> | |
) | |
} | |
export default Image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment