Toast

A short message that rises in at the bottom and leaves by itself, for success, an error or plain news, with room for one action such as Undo.

Workspace

Draft
Changes saved

Options

Size
Colour

Code

import { useEffect, useState } from "react";
import "./toast.css";

/* One toast. It calls onDone after four seconds, unless the pointer or the
   keyboard is on it.

   <Toast kind="bad" action="Try again" onAction={retry} onDone={clear}>Could not save</Toast> */
export function Toast({ kind = "info", action, onAction, onDone, children }) {
  const [held, setHeld] = useState(false);

  useEffect(() => {
    if (held || !onDone) return;
    const timer = setTimeout(onDone, 4000);
    return () => clearTimeout(timer);
  }, [held, onDone]);

  return (
    <div
      className="dh-toast"
      data-kind={kind}
      role={kind === "bad" ? "alert" : "status"}
      onPointerEnter={() => setHeld(true)}
      onPointerLeave={() => setHeld(false)}
      onFocus={() => setHeld(true)}
      onBlur={() => setHeld(false)}
    >
      <span>{children}</span>
      {action && (
        <button type="button" onClick={onAction}>
          {action}
        </button>
      )}
    </div>
  );
}

const samples = [
  { label: "Invite", kind: "info", text: "Invite sent to Maya Okafor", action: "Undo" },
  { label: "Publish", kind: "bad", text: "Could not publish", action: "Try again" },
  { label: "Save", kind: "good", text: "Changes saved", tone: "primary" },
];

export function Example() {
  const [toast, setToast] = useState({ id: 0, kind: "good", text: "Changes saved", stay: true });
  const clear = () => setToast(null);

  return (
    <div className="dh-toast-demo">
      <div className="dh-toast-card">
        <header>
          <h3>Workspace</h3>
          <em>Draft</em>
        </header>
        <label>
          <span>Name</span>
          <input type="text" defaultValue="Logoipsum studio" />
        </label>
        <footer>
          {samples.map((sample) => (
            <button
              className="dh-toast-btn"
              type="button"
              data-tone={sample.tone}
              key={sample.label}
              onClick={() => setToast({ ...sample, id: Date.now() })}
            >
              {sample.label}
            </button>
          ))}
        </footer>
      </div>
      <div className="dh-toast-area" aria-live="polite">
        {toast && (
          <Toast
            key={toast.id}
            kind={toast.kind}
            action={toast.action}
            onAction={clear}
            onDone={toast.stay ? undefined : clear}
          >
            {toast.text}
          </Toast>
        )}
      </div>
    </div>
  );
}

Workspace

Draft
Changes saved