COMPONENTS/DATA DISPLAY

Avatar.

A person, even without a picture.

In practice

CHAMJL+3

Compose AvatarImage with alt text and AvatarFallback. The fallback appears when the image is unavailable.

Installation

Install Coal once. Components and TypeScript declarations are included. React 19 and React DOM 19 are peer dependencies.

Terminal · local package
npm install http://localhost:3100/downloads/chlohal-coal-ui-0.5.0.tgz

This installs the local package. It is not yet published on npm. See installation for stylesheet setup and integration.

Usage

example.tsx
"use client";
import * as React from "react";
import "@chlohal/coal-ui/styles.css";
import { Avatar, AvatarFallback } from "@chlohal/coal-ui";
export default function Example() {
    return (<div>
          {["CH", "AM", "JL", "+3"].map((s, i) => (<Avatar key={s}>
              <AvatarFallback>{s}</AvatarFallback>
            </Avatar>))}
        </div>);
}

Source

The original Coal implementation. Use the package export to integrate it.

packages/react/src/avatar.tsx
"use client";
import * as React from "react";
import { cn, useRequired } from "./internal.js";
const Context = React.createContext<
  { loaded: boolean; setLoaded: (v: boolean) => void } | undefined
>(undefined);
export function Avatar({
  children,
  className,
  ...props
}: React.ComponentPropsWithRef<"span">) {
  const [loaded, setLoaded] = React.useState(false);
  return (
    <Context.Provider value={{ loaded, setLoaded }}>
      <span className={cn("coal-avatar", className)} {...props}>
        {children}
      </span>
    </Context.Provider>
  );
}
export function AvatarImage({
  className,
  onLoad,
  onError,
  src,
  alt,
  ...props
}: React.ComponentPropsWithRef<"img">) {
  const c = useRequired(Context, "AvatarImage");
  const { setLoaded } = c;
  React.useEffect(() => {
    setLoaded(false);
  }, [src, setLoaded]);
  return (
    <img
      {...props}
      src={src}
      alt={alt ?? ""}
      className={cn("coal-avatar-image", className)}
      style={{ display: c.loaded ? undefined : "none" }}
      onLoad={(e) => {
        c.setLoaded(true);
        onLoad?.(e);
      }}
      onError={(e) => {
        c.setLoaded(false);
        onError?.(e);
      }}
    />
  );
}
export function AvatarFallback({
  className,
  ...props
}: React.ComponentPropsWithRef<"span">) {
  const c = useRequired(Context, "AvatarFallback");
  return c.loaded ? null : (
    <span className={cn("coal-avatar-fallback", className)} {...props} />
  );
}

Accessibility checklist

  • Provide an accessible name for controls, including icon-only buttons.
  • Check keyboard navigation, visible focus and disabled states in your application.
  • Do not rely on color alone to communicate status.