Skip to content

Instantly share code, notes, and snippets.

@sriramveeraghanta
Last active December 11, 2019 15:39
Show Gist options
  • Save sriramveeraghanta/c19ef4c94bc6d42bb80624de16b6c929 to your computer and use it in GitHub Desktop.
Save sriramveeraghanta/c19ef4c94bc6d42bb80624de16b6c929 to your computer and use it in GitHub Desktop.
Image Safe Loading When src doesnt load.
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