Avatar
An image element with a fallback for representing the user. You can select a size with the size prop. Also, you can set your choice of indicator to show the status of the user.
Preview
import React from 'react';
import { AvatarRoot, AvatarFallback, AvatarImage } from "@/components/Avatar";
const avatarSrc =
"https://images.unsplash.com/photo-1492633423870-43d1cd2775eb?&w=128&h=128&dpr=2&q=80";
const App = () => {
return (
<div>
<AvatarRoot>
<AvatarImage
src={avatarSrc}
container="circle"
size="xs"
indicator={
<DotFilledIcon className="text-green-500 w-3 h-3 bottom-0 left-4 absolute" />
}
/>
<AvatarFallback>TP</AvatarFallback>
</AvatarRoot>
</div>
);
};
Examples
Install the following dependencies:
npm install @radix-ui/react-avatar
Copy and paste the following code into your project.
"use client";
import React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { VariantProps, cva } from "class-variance-authority";
import { cn } from "@/lib/utils";
const avatarVariants = cva("", {
variants: {
size: {
xs: "w-6 h-6",
sm: "w-8 h-8",
md: "w-10 h-10",
lg: "w-12 h-12",
xl: "w-14 h-14",
},
container: {
circle: "rounded-full",
square: "rounded-md",
},
},
defaultVariants: {
size: "md",
container: "circle",
},
});
interface AvatarProps extends VariantProps<typeof avatarVariants> {
src: string;
indicator?: React.ReactNode;
}
const AvatarRoot = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn("relative", className)}
{...props}
/>
));
AvatarRoot.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image> & AvatarProps
>(({ size, className, container, indicator, src, ...props }, ref) => {
const imageStyles = avatarVariants({
size,
container,
});
return (
<div className="relative">
<AvatarPrimitive.Image
ref={ref}
src={src}
className={cn(
`${imageStyles} flex items-center justify-center`,
className
)}
{...props}
/>
{indicator && (
<div className={`flex justify-center items-center z-50`}>
{indicator}
</div>
)}
</div>
);
});
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className="flex h-9 w-9 items-center justify-center rounded-full"
{...props}
/>
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { AvatarRoot, AvatarImage, AvatarFallback };