Components / FeedbackStable

Avatar

Shows who someone is with their photo or initials, and whether they are around right now.

View as Markdown

Playground

Code

Avatar.tsx
'use client'
import { useState, type CSSProperties, type HTMLAttributes, type Ref } from 'react'

// Nacre Avatar: a person as a photo or their initials, with an optional presence dot; AvatarGroup stacks a team.
// React plus Tailwind classes only; needs nacre-theme.css. Motion: the status dot changes colour quick 160 out. On a
// mouse hover over an AvatarGroup the stack fans out: each circle slides 6 px further than the one before it (translate,
// gentle 360 on the spring curve, 20 ms apart), so the overlapped initials become readable, and folds back when the
// pointer leaves; the transitions retarget, so a quick in and out never jumps. The group keeps its size. Touch, reduced
// motion and [data-nacre-motion="off"]: it stays folded.

export type AvatarSize = 'sm' | 'md' | 'lg'
export type AvatarStatus = 'online' | 'away' | 'offline'
export type AvatarPerson = { name: string; src?: string }

export type AvatarProps = Omit<HTMLAttributes<HTMLSpanElement>, 'children'> &
  AvatarPerson & { size?: AvatarSize; status?: AvatarStatus; ref?: Ref<HTMLSpanElement> }

export type AvatarRing = 'surface' | 'sunken'
export type AvatarGroupProps = { label: string; people: AvatarPerson[]; max?: number; size?: AvatarSize; /** The colour of the 2 px ring that separates overlapping circles: match the surface the group sits on. */ ring?: AvatarRing; className?: string }

// 24, 32 and 40 px; the initials scale with the circle.
const boxes: Record<AvatarSize, string> = { sm: 'size-6 text-[0.625rem]', md: 'size-8 text-caption', lg: 'size-10 text-label' }
// AvatarGroup overlap: 4 px at md and lg, 2 px at sm (spacing token steps), so the 2 px ring of the next circle
// never covers the second letter of the initials.
const overlaps: Record<AvatarSize, string> = { sm: '-space-x-0.5', md: '-space-x-1', lg: '-space-x-1' }
// The fan: circle i moves i * 6 px toward the end, 20 ms after the one before it; folding back runs in reverse order.
const fan =
  'transition-[translate] duration-(--nx-dur-gentle) ease-spring [transition-delay:calc((var(--n)_-_var(--i))*20ms)] ' +
  'motion-safe:group-hover/avatars:translate-x-[calc(var(--i)*6px)] motion-safe:group-hover/avatars:[transition-delay:calc(var(--i)*20ms)] ' +
  'rtl:motion-safe:group-hover/avatars:translate-x-[calc(var(--i)*-6px)]'
// The ring matches the surface behind the group: a panel is surface, a well or row is sunken.
const rings: Record<AvatarRing, string> = { surface: 'ring-surface', sunken: 'ring-sunken' }
const at = (i: number, n: number) => ({ '--i': i, '--n': n - 1 }) as CSSProperties
// Initials get a tint from the name (the same four pastels as Tile), so a person always keeps the same colour.
const fills = [
  'bg-linear-to-b from-tint-lime to-tint-lime-wash text-tint-lime-ink',
  'bg-linear-to-b from-tint-pink to-tint-pink-wash text-tint-pink-ink',
  'bg-linear-to-b from-tint-blue to-tint-blue-wash text-tint-blue-ink',
  'bg-linear-to-b from-tint-violet to-tint-violet-wash text-tint-violet-ink',
]
const fillFor = (name: string) => fills[[...name].reduce((n, c) => n + c.charCodeAt(0), 0) % fills.length]
const dotSizes: Record<AvatarSize, string> = { sm: 'size-2', md: 'size-2.5', lg: 'size-3' }
const statusFill: Record<AvatarStatus, string> = { online: 'bg-success', away: 'bg-warning', offline: 'bg-line-control' }

/** First letter of the first and the last word: Ana Ribeiro is AR, Chen is C. */
export function initials(name: string): string {
  const words = name.trim().split(/\s+/).filter(Boolean)
  if (words.length === 0) return ''
  return (words[0][0] + (words.length > 1 ? words[words.length - 1][0] : '')).toUpperCase()
}

export function Avatar({ name, src, size = 'md', status, className = '', ref, ...rest }: AvatarProps) {
  // A photo that fails to load falls back to the initials; a new src gets a new try.
  const [failed, setFailed] = useState<string | undefined>(undefined)
  const photo = src !== undefined && failed !== src
  return (
    <span
      ref={ref}
      role="img"
      aria-label={status ? `${name}, ${status}` : name}
      data-part="root"
      className={`relative inline-flex shrink-0 rounded-full ${boxes[size]} ${className}`}
      {...rest}
    >
      <span className={`flex size-full items-center justify-center overflow-hidden rounded-full ${fillFor(name)} leading-[1] font-[600]`}>
        {photo ? (
          // eslint-disable-next-line @next/next/no-img-element -- a copyable component, not tied to next/image
          <img src={src} alt="" onError={() => setFailed(src)} className="size-full object-cover" />
        ) : (
          <span data-part="initials" aria-hidden="true">{initials(name)}</span>
        )}
      </span>
      {status && (
        <span
          data-part="status"
          aria-hidden="true"
          className={`absolute end-0 bottom-0 rounded-full ring-2 ring-surface transition-colors duration-(--nx-dur-quick) ease-out ${dotSizes[size]} ${statusFill[status]}`}
        />
      )}
    </span>
  )
}

/** A team as overlapping avatars; past max, one more circle counts the rest. */
export function AvatarGroup({ label, people, max = 4, size = 'md', ring = 'surface', className = '' }: AvatarGroupProps) {
  const shown = people.slice(0, max)
  const more = people.length - shown.length
  const n = shown.length + (more > 0 ? 1 : 0)
  return (
    <div role="group" aria-label={label} data-part="group" className={`group/avatars flex items-center ${overlaps[size]} ${className}`}>
      {shown.map((p, i) => (
        <Avatar key={i} name={p.name} src={p.src} size={size} style={at(i, n)} className={`ring-2 ${rings[ring]} ${fan}`} />
      ))}
      {more > 0 && (
        <span
          role="img"
          aria-label={`${more} more`}
          data-part="more"
          style={at(shown.length, n)}
          className={`inline-flex shrink-0 items-center justify-center rounded-full bg-neutral-soft font-[600] text-neutral-strong ring-2 ${rings[ring]} ${fan} ${boxes[size]}`}
        >
          {`+${more}`}
        </span>
      )}
    </div>
  )
}

Usage

When to use

  • Next to a name in messages, comments and the task owner column.
  • A stack of the people on a project with AvatarGroup, where the count matters more than each name.
  • Presence in chat: online, away or offline as a small dot.

Choose something else when

  • It stands for a project or a file, not a person: use an icon or the project colour swatch.
  • The state needs a word, such as Out of office: use Badge.

In the Nacre workspace

Task owner

Each row of the task list starts with the owner as a small Avatar and their name next to it, so the face is a shortcut and the name is the label.

Project team

The project header shows an AvatarGroup with four people and a +3 circle. The group is named Q3 launch team for screen readers.

Do and don't

  • DoShow the name next to the avatar where there is room.

    Don'tMake people learn faces to tell teammates apart.

  • DoLet initials stand in when a photo is missing or fails.

    Don'tShow a generic silhouette for everyone without a photo.

Anatomy

  1. Circle. Radius full, neutral-soft fill behind the photo or initials.
  2. Initials. First letters of the first and last word in neutral-strong at weight 600, sized with the circle.
  3. Status dot. success (online), warning (away) or line-control (offline), with a 2 px surface ring to cut it out.

API

nameType stringDefault -Required. The accessible name and the source of the initials.
srcType stringDefault -Photo URL. If it fails to load, the initials show instead.
sizeType 'sm' | 'md' | 'lg'Default 'md'24, 32 or 40 px.
statusType 'online' | 'away' | 'offline'Default -A presence dot at the bottom right; the word is added to the accessible name.
...restType HTMLAttributes<HTMLSpanElement>Default -Any span attribute. Wrap it in a link or button to make it interactive.
peopleType AvatarPerson[]Default -AvatarGroup: the people to stack, as name and optional src.
maxType numberDefault 4AvatarGroup: avatars shown before the +N circle.
ringType 'surface' | 'sunken'Default 'surface'AvatarGroup: the colour of the 2 px ring between overlapping circles. Match the surface behind the group: sunken inside a well or a row.
labelType stringDefault -AvatarGroup: names the group for assistive tech, such as Q3 launch team.

Motion

Status changeProperty background-colorDuration quick 160Easing outKeyboard Same, colour only.
Group hover (mouse)Property translate: each circle 6 px further than the last, 20 ms apart, then back in reverseDuration gentle 360Easing springKeyboard None: the group is not focusable. Touch keeps it folded.
+2

Accessibility

Keyboard

None
Not interactive. For a profile link, wrap it in a link whose name is the person.

ARIA and semantics

  • role img with the name as its label, plus the status word when there is one (Ana Ribeiro, online).
  • The photo has an empty alt and the initials are aria-hidden, so the name is read once.
  • AvatarGroup is a named group; the +N circle reads as 3 more.
  • The status dot is never the only signal: the word is in the name.

Contrast

Initialsneutral-strong on neutral-softLight 12.38:1Dark 10.47:1Needs 4.5:1
The +N countfg-strong on sunkenLight 17.60:1Dark 17.91:1Needs 4.5:1
Offline dotline-control on surfaceLight 3.74:1Dark 3.72:1Needs 3:1