Animated List
An animated notification list for React and Tailwind CSS: new items fade in at the top while older ones glide down with Motion layout animations, and anything past the limit fades out. Great for notification feeds, activity logs and live landing-page demos, with polite screen reader announcements built in.
- Layout animations
- AnimatePresence popLayout
- Max visible items
- Auto stream hook
- Live region
- prefers-reduced-motion
New comment· just now
Leo: “Ship it, looks great on mobile.”
New sign-up· just now
maya@orbit.dev joined your workspace
Payment received· just now
$249.00 from Northwind Labs
"use client";
import * as React from "react";
import { useInView } from "motion/react";
import { CreditCard, GitPullRequest, MessageCircle, Pause, Play, Star, UserPlus } from "lucide-react";
import { AnimatedList, useListStream } from "@/components/dusk/animated-list/animated-list";
import { Button } from "@/components/ui/button";
const notifications = [
{ icon: CreditCard, title: "Payment received", body: "$249.00 from Northwind Labs" },
{ icon: UserPlus, title: "New sign-up", body: "maya@orbit.dev joined your workspace" },
{ icon: MessageCircle, title: "New comment", body: "Leo: “Ship it, looks great on mobile.”" },
{ icon: GitPullRequest, title: "Pull request merged", body: "#482 Add bento grid to landing page" },
{ icon: Star, title: "New review", body: "Priya rated your app 5 stars" },
];
function Notification({ icon: Icon, title, body }: (typeof notifications)[number]) {
return (
<div className="flex items-center gap-3 rounded-xl border border-white/10 bg-card p-3">
<span
aria-hidden
className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-white/[0.06] text-white/70"
>
<Icon className="size-4.5" />
</span>
<div className="min-w-0 flex-1">
<p className="flex items-center gap-2 text-sm font-medium text-white">
{title}
<span className="text-xs font-normal text-white/55">· just now</span>
</p>
<p className="truncate text-sm text-white/55">{body}</p>
</div>
</div>
);
}
export default function AnimatedListDemo() {
const ref = React.useRef<HTMLDivElement>(null);
const inView = useInView(ref);
const [paused, setPaused] = React.useState(false);
const { items } = useListStream(notifications, { initial: 3, interval: 2400, paused: paused || !inView });
return (
<div ref={ref} className="flex w-full max-w-sm flex-col gap-4">
{/* Fixed height: room for exactly `max` items, so the page never shifts. */}
<div className="h-[19rem] overflow-hidden">
<AnimatedList max={4} announcePrefix="New notification:" aria-label="Notifications">
{items.map(({ id, item }) => (
<Notification key={id} {...item} />
))}
</AnimatedList>
</div>
<Button variant="outline" size="sm" className="self-center" aria-pressed={paused} onClick={() => setPaused((p) => !p)}>
{paused ? <Play aria-hidden /> : <Pause aria-hidden />}
{paused ? "Resume stream" : "Pause stream"}
</Button>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/animated-list.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/animated-list/animated-list.tsx.animated-list.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useReducedMotion, type Transition } from "motion/react"; import { cn } from "@/lib/utils"; const layoutSpring: Transition = { type: "spring", duration: 0.35, bounce: 0.1 }; export interface AnimatedListProps extends Omit<React.HTMLAttributes<HTMLUListElement>, "children" | "onDrag" | "onDragStart" | "onDragEnd" | "onAnimationStart"> { /** Keyed elements, newest first. Each one becomes a list item. */ children: React.ReactNode; /** How many items to show. Older ones animate out. */ max?: number; /** List element to render. */ as?: "ul" | "ol"; /** Announce new items to screen readers through a polite live region. */ announce?: boolean; /** Text read before each announced item, e.g. `"New notification:"`. */ announcePrefix?: string; /** Classes for each `<li>` wrapper. */ itemClassName?: string; } /** * A notification-style list. Put the newest item first: it fades in at the * top while the items below glide down to make room (shared layout * animation), and anything past `max` fades out without taking up space * (`AnimatePresence` in `popLayout` mode). * * Give every child a stable `key`. Items present on the first render don't * animate, so server and client output match. New items are read out by a * separate polite live region (their text content), so screen readers hear * each arrival once, without the list itself re-announcing on reorder. */ export function AnimatedList({ children, max = 5, as = "ul", announce = true, announcePrefix = "", itemClassName, className, ...props }: AnimatedListProps) { const reduceMotion = useReducedMotion() ?? false; const List = as === "ol" ? motion.ol : motion.ul; const items = React.Children.toArray(children) .filter(React.isValidElement) .slice(0, Math.max(0, max)); const liveRef = React.useRef<HTMLDivElement>(null); const listRef = React.useRef<HTMLUListElement & HTMLOListElement>(null); const seen = React.useRef<Set<React.Key> | null>(null); const keySignature = items.map((item) => String(item.key)).join("|"); // Announce keys we haven't seen before. The first run only records what's there. React.useEffect(() => { const keys = keySignature ? keySignature.split("|") : []; if (seen.current === null) { seen.current = new Set(keys); return; } const fresh = keys.filter((key) => !seen.current!.has(key)); keys.forEach((key) => seen.current!.add(key)); if (!announce || !fresh.length || !liveRef.current || !listRef.current) return; const text = fresh .map((key) => listRef.current!.querySelector<HTMLElement>(`[data-key="${CSS.escape(key)}"]`)?.textContent?.trim()) .filter(Boolean) .map((t) => (announcePrefix ? `${announcePrefix} ${t}` : t)) .join(". "); if (text) liveRef.current.textContent = text; }, [keySignature, announce, announcePrefix]); return ( <> <List ref={listRef} data-slot="animated-list" className={cn("relative flex flex-col gap-3", className)} {...props}> <AnimatePresence initial={false} mode="popLayout"> {items.map((item) => ( <motion.li key={item.key} data-key={String(item.key)} layout={reduceMotion ? false : "position"} initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -8, scale: 0.97 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={ reduceMotion ? { opacity: 0, transition: { duration: 0.15 } } : { opacity: 0, scale: 0.97, transition: { duration: 0.15, ease: "easeIn" } } } transition={{ ...layoutSpring, opacity: { duration: 0.25 } }} className={cn("origin-top", itemClassName)} > {item} </motion.li> ))} </AnimatePresence> </List> {announce && <div ref={liveRef} aria-live="polite" aria-atomic="true" className="sr-only" />} </> ); } export interface UseListStreamOptions { /** Milliseconds between new items. */ interval?: number; /** How many items are kept (newest first). Keep it at or above the list's `max`. */ limit?: number; /** How many items from the source to show right away (rendered on the server too). */ initial?: number; /** Stop adding items. */ paused?: boolean; /** Start over from the first source item after the last one. */ loop?: boolean; } export interface StreamItem<T> { /** Unique, increasing id. Use it as the React key. */ id: number; item: T; } /** * Feeds an `AnimatedList` from a fixed array on a timer, for demos and * landing pages. Returns the items newest first plus `push` to add one now. * Timers start after mount and are cleared on unmount or pause. */ export function useListStream<T>( source: readonly T[], { interval = 2200, limit = 12, initial = 0, paused = false, loop = true }: UseListStreamOptions = {} ) { const [state, setState] = React.useState(() => { const count = Math.min(initial, source.length); const items: StreamItem<T>[] = []; for (let i = 0; i < count; i++) items.unshift({ id: i, item: source[i] }); return { items, next: count }; }); const push = React.useCallback(() => { setState((prev) => { if (!source.length || (!loop && prev.next >= source.length)) return prev; const entry = { id: prev.next, item: source[prev.next % source.length] }; return { items: [entry, ...prev.items].slice(0, limit), next: prev.next + 1 }; }); }, [source, loop, limit]); React.useEffect(() => { if (paused) return; const timer = window.setInterval(push, interval); return () => window.clearInterval(timer); }, [paused, interval, push]); return { items: state.items, push }; }
Usage
import { AnimatedList } from "@/components/dusk/animated-list/animated-list"
type Notification = { id: string; title: string }
export function Notifications({ items }: { items: Notification[] }) {
// Newest first. Every child needs a stable key.
return (
<AnimatedList max={5} announcePrefix="New notification:">
{items.map((n) => (
<div key={n.id} className="rounded-xl border p-3">
{n.title}
</div>
))}
</AnimatedList>
)
}Examples
Add items yourself
Prepend to your own state and the list animates. Here a paused useListStream acts as a queue: its push adds the next item. Changing max animates items in or out.
No notifications yet. Add one.
"use client";
import * as React from "react";
import { Bell, Plus } from "lucide-react";
import { AnimatedList, useListStream } from "@/components/dusk/animated-list/animated-list";
import { Button } from "@/components/ui/button";
const messages = [
"Backup completed",
"2 new followers",
"Invoice #1042 is due tomorrow",
"Your export is ready",
"Weekly report generated",
"Disk usage at 80%",
];
export default function AnimatedListManualDemo() {
const [max, setMax] = React.useState(3);
// Paused stream = a queue you push from manually.
const { items, push } = useListStream(messages, { paused: true, limit: 8 });
return (
<div className="flex w-full max-w-sm flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<Button size="sm" onClick={push}>
<Plus aria-hidden /> Add notification
</Button>
<div role="group" aria-label="Visible items" className="flex rounded-md border border-white/10 p-0.5">
{[3, 5].map((n) => (
<button
key={n}
type="button"
aria-pressed={max === n}
onClick={() => setMax(n)}
className="rounded px-2.5 py-1 text-xs text-white/60 outline-none transition-colors hover:text-white focus-visible:ring-2 focus-visible:ring-ring/50 aria-pressed:bg-white/10 aria-pressed:text-white"
>
Max {n}
</button>
))}
</div>
</div>
<div className="h-[17.5rem]">
{items.length === 0 && (
<p className="pt-10 text-center text-sm text-white/55">No notifications yet. Add one.</p>
)}
<AnimatedList max={max} className="gap-2" aria-label="Notifications">
{items.map(({ id, item }) => (
<div key={id} className="flex items-center gap-3 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2.5">
<Bell aria-hidden className="size-4 text-muted-foreground" />
<span className="text-sm text-white/80">{item}</span>
<span className="ml-auto text-xs tabular-nums text-white/55">#{id + 1}</span>
</div>
))}
</AnimatedList>
</div>
</div>
);
}Activity feed
Render an ordered list with as="ol" and restyle the gap through className. The stream pauses while the feed is off-screen.
Activity
- Preview deployedfeat/bento · 18s
- Build #1284 succeededmain · 42s
"use client";
import * as React from "react";
import { useInView } from "motion/react";
import { AnimatedList, useListStream } from "@/components/dusk/animated-list/animated-list";
const events = [
{ status: "ok", text: "Build #1284 succeeded", meta: "main · 42s" },
{ status: "info", text: "Preview deployed", meta: "feat/bento · 18s" },
{ status: "warn", text: "Cold start over budget", meta: "api/search · 820ms" },
{ status: "ok", text: "Cache warmed", meta: "32 regions" },
{ status: "error", text: "Health check failed", meta: "eu-west-2 · retrying" },
{ status: "ok", text: "Rollback complete", meta: "v2.4.1" },
] as const;
const dot: Record<(typeof events)[number]["status"], string> = {
ok: "bg-emerald-400",
info: "bg-sky-400",
warn: "bg-amber-400",
error: "bg-red-400",
};
export default function AnimatedListActivityDemo() {
const ref = React.useRef<HTMLDivElement>(null);
const inView = useInView(ref);
const { items } = useListStream(events, { initial: 2, interval: 1600, paused: !inView });
return (
<div ref={ref} className="w-full max-w-md rounded-xl border border-white/10 bg-card p-4">
<p className="mb-3 text-sm font-medium text-white/80">Activity</p>
<div className="h-[9.5rem] overflow-hidden">
<AnimatedList as="ol" max={4} className="gap-1.5" aria-label="Deployment activity">
{items.map(({ id, item }) => (
<div key={id} className="flex items-center gap-3 rounded-md bg-white/[0.03] px-3 py-2 font-mono text-xs">
<span aria-hidden className={`size-1.5 shrink-0 rounded-full ${dot[item.status]}`} />
<span className="truncate text-white/80">{item.text}</span>
<span className="ml-auto shrink-0 text-white/55">{item.meta}</span>
</div>
))}
</AnimatedList>
</div>
</div>
);
}API Reference
AnimatedList also accepts any ul / ol attribute. The file also exports useListStream(source, { interval, limit, initial, paused, loop }), which returns { items, push } with items as { id, item }, newest first, for demos and landing pages.
| Prop | Type | Default | Description |
|---|---|---|---|
| children | ReactNode | — | Keyed elements, newest first. Each is wrapped in an <li>. |
| max | number | 5 | How many items are visible. Older ones animate out. |
| as | "ul" | "ol" | "ul" | List element to render. |
| announce | boolean | true | Read new items out through a polite live region. |
| announcePrefix | string | "" | Text read before each new item, e.g. "New notification:". |
| itemClassName | string | — | Classes for each <li> wrapper. |
Accessibility
- It renders a real list (ul or ol with li), so screen readers report the item count.
- New items are announced once, by their text, through a separate polite live region. The list itself is not live, so reordering and items leaving are silent.
- Items present on the first render are not announced or animated, so the server and client render the same markup.
- Exiting items are popped out of the layout immediately and nothing measures text, so the list never jumps. Give its wrapper a fixed height for zero page shift.
- Auto-updating content should be pausable (WCAG 2.2.2): the demo uses useListStream's paused option with a button and pauses off-screen.
- With prefers-reduced-motion items only fade; there is no sliding, scaling or layout motion.