Skip to content

Instantly share code, notes, and snippets.

@stavros-melidoniotis
Created June 20, 2023 19:17
Show Gist options
  • Save stavros-melidoniotis/b737d6d84f15fa0e6ae63d04214efe33 to your computer and use it in GitHub Desktop.
Save stavros-melidoniotis/b737d6d84f15fa0e6ae63d04214efe33 to your computer and use it in GitHub Desktop.
NextJS Image component with a skeleton placeholder
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