Skip to content
Browse documentation

Where you stand and what it takes to move up: a line that fills as you close on the person above, and an overtake that swings out a lane to pass.

Used forLearning and fitness leaguesSales and support boardsGames and contestsCommunity and creators

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/leaderboard.json

Registered the namespace? Then it’s shadcn add @hairline/leaderboard. Set it up

Templates

Need the whole page?

61 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 6 are free.

All 61 templates

Where it’s used

  • Learning and fitness leagues

    Weekly leagues where the next place is the reason to do one more lesson.

  • Sales and support boards

    Deals or tickets closed this month, on a team dashboard.

  • Games and contests

    Scores in a game, a hackathon or a referral contest.

  • Community and creators

    Top contributors, streaks or points in a community.

What it handles for you

A ranked list leaves you to find yourself and work out the gap to the next place, and rows that change order jump without showing who passed whom.

Instead of wiring upa leaderboard tablea ranking lista rank change badgea progress to next rank bar
  1. The next place, measured

    A line fills as you close on the person above, with the gap rolling down.

  2. Overtakes you can see

    The climber swings out a lane and passes; the one passed drops back.

  3. Always find yourself

    Outside the top few, your row is pinned under them.

  4. Leading, too

    In first place the line becomes your lead over second.

  5. Ranks that roll

    Places and scores roll; a ▲ chip marks who climbed.

  6. Quiet for screen readers

    Your place is announced when it changes, never the scores ticking.

Overview

Leaderboards show a ranked list and leave you to work out how far the next place is. This one measures it for you. Under the board a line of hairlines sets you against the person just above: it fills as you score, while “184 XP to pass Mira” rolls down as it goes. When you pass someone, or anyone passes anyone, the climber swings out a lane, passes, and settles into its new place while the one passed drops back; the ranks roll, and a small ▲2 shows beside the climber for a moment. Outside the top few, your own row stays pinned under them, so you never scroll to find yourself. In first place the line becomes your lead over second, in green. Scores are yours: pass entries and who’s looking; the board sorts, ranks and animates whatever changed.

States

to pass
The gap to the person above (their score minus yours, plus one) rolls down; the line under it fills from where it stood when they became your target to full when you draw level (700ms per change).
overtake
Rows that change place glide from where they were (760ms). A climber swings 12px out to the right halfway, slightly larger, and comes back in at its new place, drawn over the rows it passes; a row passed dims a little as it drops. Ranks roll and a ▲ chip shows beside the climber for 2.2s.
pinned
If you’re below the top rows, three dots and your own row follow them, on a grey step.
lead
In first place the line is full and green, and says your lead over second.
reduced motion
Rows change places in place; numbers change without rolling.

Usage

usage.tsx
import { Leaderboard } from "@/components/leaderboard";<Leaderboard  title="Gold league"  period="Ends in 2 days"  unit="XP"  you={user.id}  entries={players} // { id, name, score, avatar? }[]/>

Works with

Live from your API

Poll the league every few seconds; the board animates whatever moved.

example.tsx
"use client";import useSWR from "swr";import { Leaderboard, type LeaderEntry } from "@/components/leaderboard";export function League({ leagueId, userId }: { leagueId: string; userId: string }) {  const { data } = useSWR<LeaderEntry[]>(`/api/leagues/${leagueId}`, (u: string) => fetch(u).then((r) => r.json()), { refreshInterval: 5000 });  return <Leaderboard title="Gold league" period="This week" unit="XP" you={userId} entries={data ?? []} />;}

Props

entries
LeaderEntry[]
Each entry: id, name, score, and optionally avatar. Any order; the board sorts them.
you
string
The id of the person looking: their row is highlighted or pinned, and the line measures them.
title / period
string
Over the board.
unit= "pts"
string
After every score.
top= 5
number
How many rows show before your pinned row.
locale
string
For the numbers; the visitor’s once hydrated when left out.

Accessibility and motion

  • The board is an ordered list; your row is marked aria-current; only your place is announced when it changes, never the scores.
  • Overtakes glide from measured row positions with the Web Animations API, so nothing re-renders while rows move.
  • The to-pass line is drawn in the library’s hairline mark: 2px lines every 4px, faint where empty.
  • Installs Number roll and Text morph. With reduced motion rows change places in place.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll, Text morph.

Source

components/leaderboard.tsx
"use client";import * as React from "react";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";/* ───────────────────────────────────────────────────────── * LEADERBOARD: where you stand, and what it takes to move up * *   to pass   under the board a line of hairlines measures you *             against the person just above you: it fills as you *             score, with "184 pts to pass Mira" rolling down as *             it goes. You can always see how close the next place is *   overtake  when you (or anyone) pass someone, the climber swings *             out a lane, passes, and settles in its new place while *             the one passed drops back; the ranks roll and a small *             ▲2 shows beside the climber for a moment *   pinned    outside the top few, your own row stays pinned under *             them, so you never scroll to find yourself *   lead      in first place the line becomes your lead over second * * Scores are yours: pass entries and who you are; the board sorts, * ranks and animates whatever changes. * ───────────────────────────────────────────────────────── */export interface LeaderEntry {  id: string;  name: string;  score: number;  /** An image URL; initials are drawn without one. */  avatar?: string;}export interface LeaderboardProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "title"> {  entries: LeaderEntry[];  /** The id of the person looking. */  you?: string;  title?: string;  /** e.g. "This week". */  period?: string;  /** After scores, e.g. "pts" or "XP". */  unit?: string;  /** How many rows show before your pinned row. */  top?: number;  locale?: string;}const EASE = "cubic-bezier(0.16,1,0.3,1)";const ROW = 46;const TICKS = "repeating-linear-gradient(to right, #000 0 2px, transparent 2px 4px)";const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => {  const query = window.matchMedia(reducedQuery);  query.addEventListener("change", onChange);  return () => query.removeEventListener("change", onChange);};const useReducedMotion = () =>  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);const subscribeNothing = () => () => {};const useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);const mix = (color: string, amount: number, into = "transparent") => `color-mix(in oklab, ${color} ${amount}%, ${into})`;const hue = (seed: string) => {  let h = 0;  for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0;  return `var(--chart-${(h % 5) + 1}, var(--primary))`;};const initials = (name: string) =>  name    .split(/\s+/)    .filter(Boolean)    .slice(0, 2)    .map((w) => w[0]?.toUpperCase())    .join("");export function Leaderboard({ entries, you, title = "Leaderboard", period, unit = "pts", top = 5, locale, className = "", ...props }: LeaderboardProps) {  const reduced = useReducedMotion();  const hydrated = useHydrated();  const loc = locale ?? (hydrated ? undefined : "en-US");  const ranked = React.useMemo(() => [...entries].sort((a, b) => b.score - a.score || a.name.localeCompare(b.name)), [entries]);  const rank = new Map(ranked.map((e, i) => [e.id, i + 1]));  const meIndex = you ? ranked.findIndex((e) => e.id === you) : -1;  const me = meIndex >= 0 ? ranked[meIndex] : null;  const pinned = me && meIndex >= top;  const shown = ranked.slice(0, top);  // Rank moves since the last order, kept a moment for the ▲ chips.  const orderKey = ranked.map((e) => e.id).join("|");  const [last, setLast] = React.useState({ key: orderKey, ranks: rank });  const [moves, setMoves] = React.useState<Record<string, { delta: number; live: boolean; at: number }>>({});  if (last.key !== orderKey) {    const next = { ...moves };    let stamp = Object.values(moves).reduce((m, v) => Math.max(m, v.at), 0);    ranked.forEach((e) => {      const before = last.ranks.get(e.id);      const now = rank.get(e.id)!;      if (before !== undefined && before > now) next[e.id] = { delta: before - now, live: true, at: ++stamp };    });    setMoves(next);    setLast({ key: orderKey, ranks: rank });  }  React.useEffect(() => {    const liveOnes = Object.entries(moves).filter(([, m]) => m.live);    if (!liveOnes.length) return;    const timer = window.setTimeout(() => setMoves((m) => Object.fromEntries(Object.entries(m).map(([id, v]) => [id, { ...v, live: false }]))), 2200);    return () => window.clearTimeout(timer);  }, [moves]);  // The person to pass, and how far you've closed on them since they became your target.  const target = me && meIndex > 0 ? ranked[meIndex - 1] : null;  const gap = target && me ? target.score - me.score + 1 : 0;  const lead = me && meIndex === 0 && ranked[1] ? me.score - ranked[1].score : 0;  const [start, setStart] = React.useState<{ id: string | null; gap: number }>({ id: target?.id ?? null, gap });  if ((target?.id ?? null) !== start.id) setStart({ id: target?.id ?? null, gap });  const fill = target ? Math.max(0.02, Math.min(1, 1 - gap / Math.max(1, start.id === target.id ? start.gap : gap))) : 1;  // Overtakes: rows glide from where they were; climbers swing out a lane to pass.  const rowRefs = React.useRef(new Map<string, HTMLElement>());  const tops = React.useRef(new Map<string, number>());  React.useLayoutEffect(() => {    const prev = tops.current;    const now = new Map<string, number>();    rowRefs.current.forEach((el, id) => now.set(id, el.offsetTop));    tops.current = now;    if (reduced) return;    now.forEach((y, id) => {      const from = prev.get(id);      const el = rowRefs.current.get(id);      if (from === undefined || !el || from === y) return;      const dy = from - y;      el.getAnimations().forEach((a) => a.cancel());      if (dy > 0) {        // Climbing: out a lane, past, and back in.        el.style.zIndex = "1";        const a = el.animate(          [            { transform: `translate(0, ${dy}px)` },            { transform: `translate(12px, ${dy * 0.5}px) scale(1.015)`, offset: 0.45 },            { transform: "none" },          ],          { duration: 760, easing: "cubic-bezier(0.45,0,0.2,1)" },        );        a.onfinish = a.oncancel = () => (el.style.zIndex = "");      } else {        el.animate([{ transform: `translate(0, ${dy}px)`, opacity: 1 }, { opacity: 0.7, offset: 0.5 }, { transform: "none", opacity: 1 }], { duration: 760, easing: "cubic-bezier(0.45,0,0.2,1)" });      }    });  }, [orderKey, reduced]);  const fmt = (v: number) => new Intl.NumberFormat(loc).format(v);  const row = (e: LeaderEntry, i: number, isPinned = false) => {    const mine = e.id === you;    const color = hue(e.name);    const move = moves[e.id];    const r = i + 1;    return (      <li        key={isPinned ? `${e.id}-pinned` : e.id}        ref={(el) => {          if (isPinned) return;          if (el) rowRefs.current.set(e.id, el);          else rowRefs.current.delete(e.id);        }}        className="relative flex items-center gap-2.5 rounded-[12px] px-2 @[20rem]:gap-3 @[20rem]:px-2.5"        /* Your row is a solid step of grey, no border. */        style={{ height: ROW, background: mine ? "var(--muted)" : undefined }}        aria-current={mine ? "true" : undefined}      >        <span className={`w-6 shrink-0 text-right text-[13px] tabular-nums ${r <= 3 ? "font-semibold text-foreground" : "text-muted-foreground"}`}>          <NumberRoll value={r} duration={700} />        </span>        {e.avatar ? (          // eslint-disable-next-line @next/next/no-img-element          <img src={e.avatar} alt="" className="size-7 shrink-0 rounded-full object-cover" />        ) : (          <span aria-hidden="true" className="flex size-7 shrink-0 items-center justify-center rounded-full text-[10.5px] font-semibold" style={{ background: mix(color, 20, "var(--background)"), color: mix(color, 80, "var(--foreground)") }}>            {initials(e.name)}          </span>        )}        <span className="flex min-w-0 flex-1 items-center gap-2">          <span className={`truncate text-[13.5px] ${mine ? "font-medium text-foreground" : "text-foreground"}`}>{mine ? `${e.name} (you)` : e.name}</span>          <span            aria-hidden="true"            className="shrink-0 rounded-full px-1.5 text-[10.5px] font-medium tabular-nums text-emerald-600 transition-[opacity,translate] duration-500 dark:text-emerald-400"            style={{ opacity: move?.live ? 1 : 0, translate: move?.live ? "0 0" : "0 3px", background: mix("var(--color-emerald-500, #10b981)", 12), transitionTimingFunction: EASE }}          >            ▲{move?.delta ?? 1}          </span>        </span>        <span className="shrink-0 text-[13.5px] font-medium tabular-nums text-foreground">          <NumberRoll value={e.score} locales={loc} duration={700} />          <span className="ml-1 hidden text-[11.5px] font-normal text-muted-foreground @[20rem]:inline">{unit}</span>        </span>      </li>    );  };  return (    <div className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}>      <div aria-hidden="true" data-natural-width className="grid h-0" style={{ gridTemplateColumns: "minmax(0, 400px)" }} />      <div className="@container w-full">      <div className="flex items-baseline justify-between gap-3 px-4 pb-2 pt-4 sm:px-5">        <p className="truncate text-[15px] font-medium tracking-[-0.01em] text-foreground">{title}</p>        {period && <p className="shrink-0 text-[12px] text-muted-foreground">{period}</p>}      </div>      <ol aria-label={title} className="relative px-2 sm:px-3">        {shown.map((e, i) => row(e, i))}      </ol>      {pinned && me && (        <>          <div aria-hidden="true" className="mx-5 my-1 flex justify-center gap-1">            {[0, 1, 2].map((d) => (              <span key={d} className="size-1 rounded-full bg-muted-foreground/40" />            ))}          </div>          <ol aria-label="Your place" className="px-2 sm:px-3">            {row(me, meIndex, true)}          </ol>        </>      )}      {me && (        <div className="mx-4 mb-4 mt-3 rounded-[14px] px-3.5 py-3 sm:mx-5" style={{ background: mix("var(--foreground)", 4) }}>          <p className="flex items-baseline justify-between gap-2 text-[12.5px]">            <span className="min-w-0 truncate text-muted-foreground">              {target ? (                <>                  <span className="font-medium tabular-nums text-foreground">                    <NumberRoll value={gap} locales={loc} duration={600} direction="down" />                  </span>{" "}                  {unit} to pass <TextMorph>{target.name}</TextMorph>                </>              ) : (                <>                  You lead by{" "}                  <span className="font-medium tabular-nums text-foreground">                    <NumberRoll value={lead} locales={loc} duration={600} />                  </span>{" "}                  {unit}                </>              )}            </span>            <span className="shrink-0 tabular-nums text-muted-foreground">              <TextMorph>{target ? `#${meIndex + 1} → #${meIndex}` : "#1"}</TextMorph>            </span>          </p>          <div aria-hidden="true" className="relative mt-2.5 h-3">            <div className="absolute inset-0" style={{ background: mix("var(--foreground)", 14), maskImage: TICKS, WebkitMaskImage: TICKS }} />            <div              className="absolute inset-y-0 left-0 w-full origin-left"              style={{                background: target ? "linear-gradient(90deg, var(--primary), color-mix(in oklab, var(--primary) 65%, var(--chart-3, var(--primary))))" : "var(--color-emerald-500, #10b981)",                maskImage: TICKS,                WebkitMaskImage: TICKS,                transform: `scaleX(${fill})`,                transition: reduced ? "none" : `transform 700ms ${EASE}`,              }}            />          </div>        </div>      )}      </div>      <p className="sr-only" aria-live="polite">        {/* Only your place is announced, never the scores ticking. */}        {me ? `You are in place ${fmt(meIndex + 1)}${target ? `, next to pass is ${target.name}` : ", in the lead"}.` : ""}      </p>    </div>  );}

Registry item: /r/leaderboard.json