-
-
Save ekas/5e0d42c2ab00de733d1f759b9591e2c9 to your computer and use it in GitHub Desktop.
Progressive load image component in react with hooks
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'; | |
const ImageLoad = React.memo(({ src, placeholder, alt = "" }) => { | |
const [loading, setLoading] = useState(true); | |
const [currentSrc, updateSrc] = useState(placeholder); | |
useEffect(() => { | |
// start loading original image | |
const imageToLoad = new Image(); | |
imageToLoad.src = src; | |
imageToLoad.onload = () => { | |
// When image is loaded replace the src and set loading to false | |
setLoading(false); | |
updateSrc(src); | |
} | |
}, [src]) | |
return ( | |
<img | |
src={currentSrc} | |
style={{ | |
opacity: loading ? 0.5 : 1, | |
transition: "opacity .15s linear" | |
}} | |
alt={alt} | |
/> | |
) | |
}); | |
export default ImageLoad; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment