The Avatar component is a composable component that displays user profile images with automatic fallback handling when images fail to load.
Installation
npx shadcn@latest add @eo-n/avatar
Install dependencies
npm install @base-ui/react
Copy component code
Copy and paste the following code into your project at components/ui/avatar.tsx:"use client";
import * as React from "react";
import { Avatar as AvatarPrimitive } from "@base-ui/react";
import { cn } from "@/lib/utils";
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
);
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
);
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props}
/>
);
}
export { Avatar, AvatarImage, AvatarFallback };
Update imports
Update the import paths to match your project setup.
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
<Avatar>
<AvatarImage src="https://github.com/aeonzz.png" alt="@aeonz" />
<AvatarFallback>AE</AvatarFallback>
</Avatar>
Examples
Basic Avatar
<Avatar>
<AvatarImage src="https://github.com/aeonzz.png" />
<AvatarFallback>AE</AvatarFallback>
</Avatar>
With Fallback
When the image fails to load, the fallback content is displayed:
<Avatar>
<AvatarImage src="/invalid-image.png" />
<AvatarFallback>JD</AvatarFallback>
</Avatar>
Custom Size
<Avatar className="size-12">
<AvatarImage src="https://github.com/aeonzz.png" />
<AvatarFallback>AE</AvatarFallback>
</Avatar>
Component API
The root container component.
Additional CSS classes to apply to the avatar container.
...props
React.ComponentProps<typeof AvatarPrimitive.Root>
All props from Base UI Avatar.Root component.
AvatarImage
Displays the avatar image.
Alternative text for the image.
Additional CSS classes to apply to the image.
AvatarFallback
Displays fallback content when the image fails to load.
The fallback content (usually initials).
Additional CSS classes to apply to the fallback.
Reference
Built on top of Base UI Avatar.