Created
December 12, 2019 16:35
-
-
Save bad6e/123d6da7ce26c54805452dc7fb9a99d1 to your computer and use it in GitHub Desktop.
Lazy Load Image React
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 React, { useState, useEffect } from 'react' | |
import AspectRatio from 'react-aspect-ratio' | |
import handleViewport from 'react-in-viewport' | |
import BootstrapImage from 'react-bootstrap/Image' | |
// Utils | |
import { INIT, LOADING, LOADED } from '../../utils/constants' | |
// Scss | |
import './lazyImage.scss' | |
const ImageObject = (props) => { | |
const { | |
alt, | |
className, | |
forwardedRef, | |
inViewport, | |
ratio, | |
fluid, | |
src: originalSrc, | |
} = props | |
const [src, setSrc] = useState('') | |
const [status, setStatus] = useState(INIT) | |
const [datasrc, setDataSrc] = useState('') | |
const loadImage = imageSrc => { | |
const img = new Image() | |
setStatus(LOADING) | |
img.onload = () => { | |
setSrc(imageSrc) | |
setStatus(LOADED) | |
setDataSrc('fade-in') | |
} | |
img.src = imageSrc | |
img.alt = alt | |
} | |
useEffect(() => { | |
if (inViewport && status === INIT) { | |
loadImage(originalSrc) | |
} | |
}, [inViewport, status, loadImage, originalSrc]) | |
return ( | |
<AspectRatio | |
ratio={ratio} | |
ref={forwardedRef} | |
> | |
<BootstrapImage | |
alt={alt} | |
src={src} | |
className={`${className} lazy-image`} | |
fluid={fluid} | |
datasrc={datasrc} | |
/> | |
</AspectRatio> | |
) | |
} | |
const LazyImage = handleViewport(ImageObject, {}, { disconnectOnLeave: true }) | |
export default LazyImage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment