Skip to content

Commit

Permalink
refactor: blur image component
Browse files Browse the repository at this point in the history
  • Loading branch information
mfts committed Jul 19, 2024
1 parent 50e153a commit 2f8d749
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 28 deletions.
23 changes: 15 additions & 8 deletions components/blur-image.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,33 @@
"use client";

import Image, { ImageProps } from "next/image";

import { useEffect, useState } from "react";

export default function BlurImage(props: ImageProps) {
import { cn } from "@/lib/utils";

export function BlurImage(props: ImageProps) {
const [loading, setLoading] = useState(true);
const [src, setSrc] = useState(props.src);
useEffect(() => setSrc(props.src), [props.src]); // update the `src` value when the `prop.src` value changes

const handleLoad = (e: React.SyntheticEvent<HTMLImageElement, Event>) => {
setLoading(false);
const target = e.target as HTMLImageElement;
if (target.naturalWidth <= 16 && target.naturalHeight <= 16) {
setSrc(`https://avatar.vercel.sh/${encodeURIComponent(props.alt)}`);
}
};

return (
<Image
{...props}
src={src}
alt={props.alt}
className={`${props.className} ${loading ? "blur-[2px]" : "blur-0"}`}
onLoad={async () => {
setLoading(false);
}}
className={cn(loading ? "blur-[2px]" : "blur-0", props.className)}
onLoad={handleLoad}
onError={() => {
setSrc(`https://avatar.vercel.sh/${props.alt}`); // if the image fails to load, use the default avatar
setSrc(`https://avatar.vercel.sh/${encodeURIComponent(props.alt)}`); // if the image fails to load, use the default avatar
}}
unoptimized
/>
);
}
20 changes: 0 additions & 20 deletions components/shared/blur-image.tsx

This file was deleted.

0 comments on commit 2f8d749

Please sign in to comment.