Avatar and avatar group

A round photo that falls back to the person's initials, in three sizes and with a status dot, and a stacked group that ends with a count of who is left over. Shown in a small list of people.

People with access

MO JW PN TH +3

Options

Size
Colour

Code

import { useState } from "react";
import "./avatar.css";

const initials = (name) =>
  name
    .split(" ")
    .map((word) => word[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

/* <Avatar name="Maya Okafor" src="/maya.jpg" size="lg" status="online" />
   The initials show when there is no photo or it fails to load.
   size is "sm" or "lg"; status is "online" or "away". */
export function Avatar({ name, src, size, status }) {
  const [failed, setFailed] = useState(false);
  return (
    <span className="dh-avatar" data-size={size} data-status={status} role="img" aria-label={status ? name + ", " + status : name}>
      {initials(name)}
      {src && !failed && <img src={src} alt="" onError={() => setFailed(true)} />}
    </span>
  );
}

/* Shows the first few people, then how many more there are. */
export function AvatarGroup({ people, max = 4, size }) {
  const more = people.length - max;
  return (
    <div className="dh-avatar-group" role="group" aria-label={people.length + " people"}>
      {people.slice(0, max).map((person) => (
        <Avatar key={person.name} name={person.name} src={person.src} size={size} />
      ))}
      {more > 0 && (
        <span className="dh-avatar dh-avatar-more" data-size={size} role="img" aria-label={more + " more"}>
          +{more}
        </span>
      )}
    </div>
  );
}

const team = [
  { name: "Maya Okafor", src: "/blocks/dash-face-1.jpg", email: "[email protected]", role: "Owner", status: "online" },
  { name: "Jonas Weber", email: "[email protected]", role: "Admin" },
  { name: "Priya Nair", src: "/blocks/dash-face-3.jpg", email: "[email protected]", role: "Member", status: "away" },
  { name: "Tom Hale", src: "/blocks/dash-face-4.jpg" },
  { name: "Ana Ruiz" },
  { name: "Lee Park" },
  { name: "Sam Cole" },
];

export function Example() {
  return (
    <div className="dh-avatar-card">
      <header>
        <h3>People with access</h3>
        <AvatarGroup people={team} size="sm" />
      </header>
      <ul>
        {team.slice(0, 3).map((person) => (
          <li key={person.name}>
            <Avatar name={person.name} src={person.src} status={person.status} />
            <p>
              <b>{person.name}</b>
              <span>{person.email}</span>
            </p>
            <em>{person.role}</em>
          </li>
        ))}
      </ul>
    </div>
  );
}

People with access

MO JW PN TH +3