Specification
- Catalogue
- No. 77 of 110
- Section
- Overlays and toasts
- Interaction
- Feedback, Layout Animation
- Element
- Toast
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
New toasts arrive at the front and push older ones back. Behind the first, each toast is shifted up by 12px and scaled down by 5 percent, so three messages take the height of one.
Hovering or focusing the stack fans it out to full spacing, and the same transition runs in reverse when the pointer leaves. Every toast's position comes from its index in a custom property, so adding or removing one re-flows the rest with no extra code.
Toasts dismiss themselves after four seconds and each has a close button. A fourth toast fades the oldest out rather than stacking forever.
Code
React and plain CSS"use client";
import { useEffect, useRef, useState, type CSSProperties } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import styles from "./toast-stack.module.css";
type Toast = { id: number; text: string; leaving?: boolean };
const MESSAGES = ["Changes saved", "Link copied", "Invite sent", "File uploaded"];
const VISIBLE = 3;
const LIFETIME = 4000;
/** Card demo: how many toasts are up at each step, and whether the stack is fanned out. */
const DEMO = [
{ count: 1, open: false },
{ count: 2, open: false },
{ count: 3, open: false },
{ count: 3, open: true },
{ count: 0, open: false },
];
export default function ToastStack({ active, context }: LivePreviewProps) {
const [toasts, setToasts] = useState<Toast[]>([]);
const [hovered, setHovered] = useState(false);
const [step, setStep] = useState(0);
const nextId = useRef(0);
const timers = useRef(new Set<number>());
const demo = active && context === "card";
// Each time the demo starts, it starts from the first step.
const [demoRunning, setDemoRunning] = useState(demo);
if (demoRunning !== demo) {
setDemoRunning(demo);
setStep(0);
}
useEffect(() => {
if (!demo) return;
const id = window.setInterval(() => setStep((s) => s + 1), 1000);
return () => window.clearInterval(id);
}, [demo]);
useEffect(() => {
const pending = timers.current;
return () => pending.forEach((t) => window.clearTimeout(t));
}, []);
function later(fn: () => void, ms: number) {
const t = window.setTimeout(() => {
timers.current.delete(t);
fn();
}, ms);
timers.current.add(t);
}
function dismiss(id: number) {
setToasts((list) => list.map((t) => (t.id === id ? { ...t, leaving: true } : t)));
later(() => setToasts((list) => list.filter((t) => t.id !== id)), 300);
}
function push() {
const id = nextId.current++;
const text = MESSAGES[id % MESSAGES.length] ?? "Done";
setToasts((list) => [{ id, text }, ...list].slice(0, VISIBLE + 1));
later(() => dismiss(id), LIFETIME);
}
const demoState = DEMO[step % DEMO.length] ?? { count: 0, open: false };
const list: Toast[] =
context === "card"
? demo
? Array.from({ length: demoState.count }, (_, i) => ({ id: demoState.count - 1 - i, text: MESSAGES[demoState.count - 1 - i] ?? "" }))
: []
: toasts;
const open = context === "card" ? demo && demoState.open : hovered;
return (
<div className={styles.root}>
<button type="button" className={styles.trigger} onClick={push} tabIndex={context === "card" ? -1 : 0}>
Show a toast
</button>
<ol
className={styles.stack}
data-open={open ? "" : undefined}
aria-live="polite"
onPointerEnter={() => setHovered(true)}
onPointerLeave={() => setHovered(false)}
onFocus={() => setHovered(true)}
onBlur={() => setHovered(false)}
>
{list.map((toast, index) => (
<li
key={toast.id}
className={styles.toast}
data-hidden={index >= VISIBLE || toast.leaving ? "" : undefined}
style={{ "--i": index } as CSSProperties}
>
<span className={styles.icon} aria-hidden="true">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none">
<path d="m5 12.5 4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
<span className={styles.text}>{toast.text}</span>
{context === "detail" && (
<button type="button" className={styles.close} onClick={() => dismiss(toast.id)} aria-label={`Dismiss ${toast.text}`}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M6 6l12 12M18 6 6 18" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" />
</svg>
</button>
)}
</li>
))}
</ol>
</div>
);
}