Last active
December 11, 2019 15:39
-
-
Save sriramveeraghanta/c19ef4c94bc6d42bb80624de16b6c929 to your computer and use it in GitHub Desktop.
Image Safe Loading When src doesnt load.
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 from "react"; | |
function useFallbackImageInSSR(fallbackSrc) { | |
const ref = React.useRef(null); | |
const onError = React.useCallback( | |
event => { | |
event.target.src = fallbackSrc; | |
}, | |
[fallbackSrc] | |
); | |
React.useEffect(() => { | |
if (ref && ref.current) { | |
const { complete, naturalHeight } = ref.current; | |
const errorLoadingImgBeforeHydration = complete && naturalHeight === 0; | |
if (errorLoadingImgBeforeHydration) { | |
ref.current.src = fallbackSrc; | |
} | |
} | |
}, [fallbackSrc]); | |
return { | |
ref, | |
onError | |
}; | |
} | |
export default function EventImage({ path }) { | |
const fallbackImageProps = useFallbackImageInSSR( | |
"/static/default.jpeg" | |
); | |
return ( | |
<img | |
src="/static/image-not-found.jpg" | |
alt="Image not Found" | |
{...fallbackImageProps} | |
/> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment