Avatar Image
MediaCircular avatar image with fallback placeholder.
Preview
?
?
?
Usage
example.jsx
import { AvatarImage } from "@/components/ui/avatar-image";
export default function Example() {
return <AvatarImage />;
}Source Code
Copy this file into components/ui/avatar-image.jsx in your project.
avatar-image.jsx
"use client";
import { forwardRef, useState } from "react";
import { cn } from "@/lib/utils";
const AvatarImage = forwardRef(({ className, src, alt = "", fallback, size = "md", ...props }, ref) => {
const [error, setError] = useState(false);
const sizes = { sm: "h-8 w-8", md: "h-10 w-10", lg: "h-14 w-14", xl: "h-20 w-20" };
return (
<div ref={ref} className={cn("relative inline-flex shrink-0 overflow-hidden rounded-full", sizes[size], className)} {...props}>
{!error && src ? (
<img src={src} alt={alt} className="aspect-square h-full w-full object-cover" onError={() => setError(true)} />
) : (
<div className="flex h-full w-full items-center justify-center bg-muted text-sm font-medium text-muted-foreground">
{fallback || alt?.charAt(0)?.toUpperCase() || "?"}
</div>
)}
</div>
);
});
AvatarImage.displayName = "AvatarImage";
export { AvatarImage };
Quick Install
Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.
npm install clsx tailwind-merge