Last active
November 13, 2022 16:13
-
-
Save tera-ny/538378df6fe91e1652932ce7ba5d3290 to your computer and use it in GitHub Desktop.
Component to preload images
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 { FC, PropsWithChildren, ReactNode, useEffect, useState } from "react"; | |
interface Props { | |
srcSets: { [key: string]: string }; | |
fallback?: ReactNode; | |
} | |
const Preload: FC<PropsWithChildren<Props>> = ({ | |
children, | |
fallback, | |
srcSets, | |
}) => { | |
const [isLoaded, setIsLoaded] = useState(false); | |
useEffect(() => { | |
Promise.all( | |
Object.values(srcSets).map( | |
(src) => | |
new Promise<void>((resolve) => { | |
const img = new Image(); | |
img.onload = () => { | |
resolve(); | |
}; | |
img.src = src; | |
}) | |
) | |
).then(() => { | |
setIsLoaded(true); | |
}); | |
}, [srcSets]); | |
if (isLoaded) { | |
return <>{children}</>; | |
} else { | |
return <>{fallback}</>; | |
} | |
}; | |
export default Preload; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment