Skip to content

Instantly share code, notes, and snippets.

@sambeevors
Created February 9, 2020 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sambeevors/c096b96e3b0efe2c60b6c20a53213e77 to your computer and use it in GitHub Desktop.
Save sambeevors/c096b96e3b0efe2c60b6c20a53213e77 to your computer and use it in GitHub Desktop.
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