Skip to content

Instantly share code, notes, and snippets.

@sambeevors
Created Feb 9, 2020
Embed
What would you like to do?
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