Created
June 20, 2023 19:17
-
-
Save stavros-melidoniotis/b737d6d84f15fa0e6ae63d04214efe33 to your computer and use it in GitHub Desktop.
NextJS Image component with a skeleton placeholder
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 Image, { ImageProps } from "next/image"; | |
import { ReactNode, useState } from "react"; | |
interface ISkeletonImageProps extends ImageProps { | |
skeleton: ReactNode; | |
} | |
const SkeletonImage = ({ skeleton, ...props }: ISkeletonImageProps) => { | |
const [showSkeleton, setShowSkeleton] = useState<boolean>(true); | |
const { alt, width, height, src, className } = props; | |
return ( | |
<div> | |
<Image | |
width={width} | |
height={height} | |
className={`${className} ${ | |
showSkeleton ? "opacity-0 absolute" : "opacity-1 relative" | |
}`} | |
src={src} | |
alt={alt} | |
placeholder="empty" | |
onLoadingComplete={() => { | |
setShowSkeleton(false); | |
}} | |
/> | |
{showSkeleton ? <div className="animate-pulse"> {skeleton} </div> : null} | |
</div> | |
); | |
}; | |
export default SkeletonImage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment