Skip to content
Shaken UI
Sign in

Avatar

Save

An avatar with an image, an initials fallback, five sizes, a presence dot, and an AvatarGroup that collapses extras into a count, built on Base UI Avatar.

Category
Data display
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Avatar preview
6 reviewers on this run

Installation

npx @shakenui/cli add avatar

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add avatar --dry-run

Usage

avatar-example.tsx
import { Avatar, AvatarGroup } from "@/components/shaken/ui/avatar";

// An inline portrait so the example works offline. Real apps pass a photo URL.
const portrait =
  "data:image/svg+xml;utf8," +
  encodeURIComponent(
    '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" fill="#d6d3d1"/><circle cx="32" cy="26" r="11" fill="#78716c"/><path d="M12 64c2-13 10-20 20-20s18 7 20 20z" fill="#57534e"/></svg>',
  );

const reviewers = ["Mara Okafor", "Jonas Weber", "Priya Raman", "Leo Martins", "Aiko Tanaka", "Sam Ortiz"];

function BotGlyph() {
  return (
    <svg viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <rect x="2.75" y="5" width="10.5" height="8" rx="2.5" stroke="currentColor" strokeWidth="1.5" />
      <path d="M8 2.5V5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      <circle cx="6" cy="9" r="1" fill="currentColor" />
      <circle cx="10" cy="9" r="1" fill="currentColor" />
    </svg>
  );
}

export default function AvatarExample() {
  return (
    <div className="grid justify-items-center gap-8">
      <div className="flex items-end gap-4">
        <Avatar size="xs" name="Mara Okafor" />
        <Avatar size="sm" name="Jonas Weber" status="online" />
        <Avatar size="md" name="Priya Raman" src={portrait} status="away" />
        <Avatar size="lg" name="Release bot" fallback={<BotGlyph />} status="working" />
        <Avatar size="xl" name="Acme Labs" shape="square" />
      </div>
      <div className="flex items-center gap-3">
        <AvatarGroup label="Reviewers" max={4}>
          {reviewers.map((name) => (
            <Avatar key={name} name={name} />
          ))}
        </AvatarGroup>
        <span className="text-sm text-zinc-600 dark:text-zinc-400">6 reviewers on this run</span>
      </div>
    </div>
  );
}

API

PropTypeDefaultDescription
Avatar namestring—Person or agent name: the initials and the accessible name.
Avatar srcstring—Image URL. Initials show while it loads or if it fails.
Avatar size"xs" | "sm" | "md" | "lg" | "xl""md"20, 24, 32, 40, or 56 pixels.
Avatar status"online" | "away" | "busy" | "offline" | "working"—Presence dot cut out by a ring in the page color. working marks an agent doing work.
Avatar shape"circle" | "square""circle"Square suits organizations and workspaces.
Avatar fallbackReactNode—Replaces the initials, for example with an icon.
Avatar fallbackDelaynumber300Milliseconds before initials show while an image loads.
AvatarGroup max / size / labelnumber / AvatarSize / string—Avatars to show before a +N count, the size for all, and the group's accessible name.

Accessibility

  • Each avatar is one image (role="img") named after the person, including status ("Jonas Weber, online"); the inner image and initials are hidden from assistive technology.
  • The overflow count is named "2 more: Aiko Tanaka, Sam Ortiz" and lists the names in its tooltip.
  • Status reads in the accessible name, not by color alone.
  • The photo fades in over 200ms when it loads; reduced motion shows it at once.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/avatar.tsxavatar
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/avatar/0.1.0.json.

ui/avatar.tsxShow
ui/avatar.tsx
"use client";

import { Avatar as BaseAvatar } from "@base-ui/react/avatar";
import { Children, type ComponentProps, createContext, isValidElement, type ReactNode, useContext } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const sizes = {
  xs: { box: "size-5 text-[9px]", dot: "size-1.5 ring-[1.5px]", overlap: "[&>*+*]:-ms-0.5" },
  sm: { box: "size-6 text-[10px]", dot: "size-2 ring-[1.5px]", overlap: "[&>*+*]:-ms-1" },
  md: { box: "size-8 text-xs", dot: "size-2.5 ring-2", overlap: "[&>*+*]:-ms-1.5" },
  lg: { box: "size-10 text-sm", dot: "size-3 ring-2", overlap: "[&>*+*]:-ms-2" },
  xl: { box: "size-14 text-base", dot: "size-3.5 ring-[2.5px]", overlap: "[&>*+*]:-ms-3" },
} as const;

export type AvatarSize = keyof typeof sizes;

const statuses = {
  online: { dot: "bg-emerald-500", label: "Online" },
  away: { dot: "bg-amber-500", label: "Away" },
  busy: { dot: "bg-red-500", label: "Busy" },
  offline: { dot: "bg-zinc-400 dark:bg-zinc-500", label: "Offline" },
  // For agents: the avatar is doing work right now.
  working: { dot: "bg-sky-500", label: "Working" },
} as const;

export type AvatarStatus = keyof typeof statuses;

const GroupContext = createContext<{ size: AvatarSize; grouped: boolean } | null>(null);

/** First letter of the first and last word: "Mara Okafor" becomes "MO", "deploy-bot" becomes "D". */
export function getInitials(name: string) {
  const words = name.trim().split(/\s+/).filter(Boolean);
  const first = words[0]?.[0] ?? "";
  const last = words.length > 1 ? (words[words.length - 1]?.[0] ?? "") : "";
  return (first + last).toUpperCase();
}

export interface AvatarProps extends Omit<ComponentProps<"span">, "children"> {
  /** Image URL. While it loads, or if it fails, the initials show instead. */
  src?: string;
  /** The person's or agent's name. Used for the initials and the accessible name. */
  name: string;
  size?: AvatarSize;
  /** A presence dot at the bottom right, cut out of the avatar by a ring in the page color. */
  status?: AvatarStatus;
  /** Replaces the initials, for example with an icon for a bot or a team. */
  fallback?: ReactNode;
  /** Square corners suit organizations and workspaces; people stay round. */
  shape?: "circle" | "square";
  /** Milliseconds to wait before showing the fallback, so fast images do not flash initials first. */
  fallbackDelay?: number;
}

/**
 * A profile picture with an initials fallback, built on Base UI Avatar. Announced as one image
 * named after the person, including their status when one is set.
 */
export function Avatar({
  src,
  name,
  size: sizeProp,
  status,
  fallback,
  shape = "circle",
  fallbackDelay,
  className,
  ...props
}: AvatarProps) {
  const group = useContext(GroupContext);
  const size = sizeProp ?? group?.size ?? "md";
  const radius = shape === "circle" ? "rounded-full" : size === "xs" || size === "sm" ? "rounded-[5px]" : "rounded-lg";
  const label = status ? `${name}, ${statuses[status].label.toLowerCase()}` : name;

  return (
    <span
      role="img"
      aria-label={label}
      data-slot="avatar"
      data-status={status}
      className={cx("relative inline-flex shrink-0 align-middle", className)}
      {...props}
    >
      <BaseAvatar.Root
        aria-hidden="true"
        className={cx(
          "relative inline-flex items-center justify-center overflow-hidden font-medium select-none",
          // A tint layered over the page color: reads as a soft fill, yet stays opaque where avatars overlap.
          "bg-white bg-linear-to-b from-zinc-950/[0.05] to-zinc-950/[0.05] text-zinc-600",
          "dark:bg-black dark:from-white/[0.09] dark:to-white/[0.09] dark:text-zinc-300",
          // A hairline inside the edge keeps light photos from bleeding into a white page.
          "after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:border after:border-zinc-950/10 dark:after:border-white/10",
          group?.grouped && "ring-2 ring-white dark:ring-black",
          sizes[size].box,
          radius,
        )}
      >
        {src ? (
          <BaseAvatar.Image
            src={src}
            alt=""
            className={cx(
              "size-full object-cover",
              "transition-opacity duration-200 ease-out motion-reduce:transition-none data-[starting-style]:opacity-0",
            )}
          />
        ) : null}
        <BaseAvatar.Fallback delay={src ? fallbackDelay ?? 300 : 0} className="leading-none [&_svg]:size-[55%]">
          {fallback ?? getInitials(name)}
        </BaseAvatar.Fallback>
      </BaseAvatar.Root>
      {status ? (
        <span
          aria-hidden="true"
          className={cx(
            "absolute right-0 bottom-0 rounded-full ring-white dark:ring-black",
            shape === "square" && "translate-x-1/4 translate-y-1/4",
            "transition-[background-color] duration-200 ease-out motion-reduce:transition-none",
            statuses[status].dot,
            sizes[size].dot,
          )}
        />
      ) : null}
    </span>
  );
}

export interface AvatarGroupProps extends ComponentProps<"div"> {
  /** Size for every avatar in the group. */
  size?: AvatarSize;
  /** How many avatars to show before collapsing the rest into a `+N` count. */
  max?: number;
  /** Accessible name for the group, for example "Reviewers". */
  label?: string;
}

/**
 * Overlapping avatars with an overflow count. Each avatar is ringed in the page color so the
 * overlap reads as a stack. The count lists the hidden names in its tooltip and accessible name.
 */
export function AvatarGroup({ size = "md", max, label, className, children, ...props }: AvatarGroupProps) {
  const items = Children.toArray(children).filter(isValidElement);
  const visible = max != null && items.length > max ? items.slice(0, Math.max(0, max)) : items;
  const hidden = items.slice(visible.length);
  const hiddenNames = hidden
    .map((item) => (item.props as { name?: unknown }).name)
    .filter((value): value is string => typeof value === "string");

  return (
    <GroupContext.Provider value={{ size, grouped: true }}>
      <div role="group" aria-label={label} data-slot="avatar-group" className={cx("flex items-center", sizes[size].overlap, className)} {...props}>
        {visible}
        {hidden.length > 0 ? (
          <span
            role="img"
            aria-label={`${hidden.length} more${hiddenNames.length ? `: ${hiddenNames.join(", ")}` : ""}`}
            title={hiddenNames.length ? hiddenNames.join(", ") : undefined}
            className={cx(
              "relative inline-flex shrink-0 items-center justify-center rounded-full font-medium tabular-nums select-none",
              "bg-white text-zinc-600 ring-2 ring-white dark:bg-black dark:text-zinc-300 dark:ring-black",
              "after:pointer-events-none after:absolute after:inset-0 after:rounded-full after:border after:border-zinc-950/12 dark:after:border-white/15",
              sizes[size].box,
            )}
          >
            <span aria-hidden="true">+{hidden.length}</span>
          </span>
        ) : null}
      </div>
    </GroupContext.Provider>
  );
}