Skip to content

Instantly share code, notes, and snippets.

@brijr
Created February 20, 2025 17:39
Show Gist options
  • Save brijr/5d4b35ef92298307b80f0798f15643c2 to your computer and use it in GitHub Desktop.
Save brijr/5d4b35ef92298307b80f0798f15643c2 to your computer and use it in GitHub Desktop.
React Async Image Component
"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>
);
}
@brijr
Copy link
Author

brijr commented Feb 20, 2025

Example usage can be found on oat.club

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment