Created
February 20, 2025 17:39
-
-
Save brijr/5d4b35ef92298307b80f0798f15643c2 to your computer and use it in GitHub Desktop.
React Async Image Component
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
"use client"; | |
import React, { useState, useEffect } from "react"; | |
import { cn } from "@/lib/utils"; | |
interface AsyncImageProps extends React.ImgHTMLAttributes<HTMLImageElement> { | |
width: number; | |
height: number; | |
} | |
export function AsyncImage({ | |
width, | |
height, | |
className, | |
src, | |
alt = "Product image", | |
...props | |
}: AsyncImageProps) { | |
const [isLoaded, setIsLoaded] = useState(false); | |
const aspectRatio = width / height; | |
useEffect(() => { | |
const img = new Image(); | |
img.src = src as string; | |
if (img.complete) { | |
setIsLoaded(true); | |
} | |
}, [src]); | |
return ( | |
<div | |
className={cn( | |
"relative w-full transition-all duration-500", | |
isLoaded ? "bg-transparent" : "bg-gray-300 blur-lg" | |
)} | |
style={{ paddingTop: `${(1 / aspectRatio) * 100}%` }} | |
> | |
<img | |
src={src} | |
alt={alt} | |
width={width} | |
height={height} | |
onLoad={() => setIsLoaded(true)} | |
className={cn( | |
"absolute top-0 left-0 w-full h-full object-cover transition-opacity duration-500", | |
isLoaded ? "opacity-100" : "opacity-0", | |
className | |
)} | |
{...props} | |
/> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage can be found on oat.club