Avatar

Base

User avatar with image and fallback initials support.

Preview

UserCNPUABSM

Usage

example.jsx
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";

export default function Example() {
  return <Avatar />;
}

Source Code

Copy this file into components/ui/avatar.jsx in your project.

avatar.jsx
"use client";

import { forwardRef, useState } from "react";
import { cn } from "@/lib/utils";

const Avatar = forwardRef(({ className, ...props }, ref) => (
  <span
    ref={ref}
    className={cn(
      "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
      className
    )}
    {...props}
  />
));
Avatar.displayName = "Avatar";

const AvatarImage = forwardRef(({ className, src, alt, ...props }, ref) => {
  const [hasError, setHasError] = useState(false);

  if (hasError || !src) return null;

  return (
    <img
      ref={ref}
      src={src}
      alt={alt}
      className={cn("aspect-square h-full w-full", className)}
      onError={() => setHasError(true)}
      {...props}
    />
  );
});
AvatarImage.displayName = "AvatarImage";

const AvatarFallback = forwardRef(({ className, ...props }, ref) => (
  <span
    ref={ref}
    className={cn(
      "flex h-full w-full items-center justify-center rounded-full bg-muted",
      className
    )}
    {...props}
  />
));
AvatarFallback.displayName = "AvatarFallback";

export { Avatar, AvatarImage, AvatarFallback };

Quick Install

Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.

npm install clsx tailwind-merge