Components
Avatar
Avatar component
DR
Installation
Copy and paste the following code into your project.
"use client";
import { cn } from "@/lib/utils";
import { forwardRef, useState, HTMLAttributes } from "react";
interface AvatarProps extends HTMLAttributes<HTMLDivElement> {
/** Image source URL */
src?: string;
/** Full name for generating initials */
name?: string;
/** Custom CSS class names */
className?: string;
/** Avatar size: sm (32px), md (40px), lg (48px), xl (64px) */
size?: "sm" | "md" | "lg" | "xl";
}
const UserIcon = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="100%"
height="100%"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="8" r="5"></circle>
<path d="M20 21a8 8 0 0 0-16 0"></path>
</svg>
);
const Avatar = forwardRef<HTMLDivElement, AvatarProps>(
({ src, name = "", className = "", size = "md", ...props }, ref) => {
const getInitials = (name: string): string => {
if (!name) return "";
const nameParts = name.trim().split(" ");
if (nameParts.length === 1) {
return nameParts[0].charAt(0).toUpperCase();
}
const firstInitial = nameParts[0].charAt(0);
const lastInitial = nameParts[nameParts.length - 1].charAt(0);
return (firstInitial + lastInitial).toUpperCase();
};
const sizeClasses = {
sm: "size-8",
md: "size-10",
lg: "size-12",
xl: "size-16",
};
const sizeClass = sizeClasses[size] || sizeClasses.md;
const [imgError, setImgError] = useState<boolean>(false);
const handleError = (): void => {
setImgError(true);
};
const showFallback = !src || imgError;
const initials = getInitials(name);
return (
<div
ref={ref}
className={cn(
"inline-flex select-none items-center justify-center overflow-hidden rounded-full bg-gray-100 align-middle ",
sizeClass,
className
)}
{...props}
>
{!showFallback ? (
<img
src={src}
alt={name || "Avatar"}
className="h-full w-full object-cover"
onError={handleError}
/>
) : initials ? (
<div className="flex h-full w-full items-center justify-center bg-gray-200 text-gray-600 font-medium">
{initials}
</div>
) : (
<div className="flex h-full w-full items-center justify-center bg-gray-200 text-gray-400">
<UserIcon />
</div>
)}
</div>
);
}
);
Avatar.displayName = "Avatar";
export default Avatar;
Update the import paths to match your project setup.
Usage
import Avatar from "@/components/ui/avatar";
<Avatar
src="https://avatars.githubusercontent.com/u/85922349?v=4"
name="Dilkhush Raj"
className="w-20 h-20"
/>
<Avatar name="Dilkhush Raj" className="w-20 ml-4 h-20" />
Props
Props | Type | Default | Description |
---|---|---|---|
src | string | Image source URL | |
name | string | Full name for generating initials | |
className | string | Custom CSS class names | |
size | "sm" | "md" | "lg" | "xl" | "md" | Avatar size: sm (32px), md (40px), lg (48px), xl (64px) |