Created
July 19, 2020 15:14
-
-
Save nirajrajgor/f00a7a05d662c89feb666023a62678f0 to your computer and use it in GitHub Desktop.
Progressive load image component in react with hooks
This file contains hidden or 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