Menu

Components

Bar List

A list of things with a bar for each: the pages that got the most visits, the countries of your users, the products that sold best.

Introduction

Bar List is a ranking you can read at a glance: each row has a name, a number, and a bar as long as the number. Use it for the pages with the most visits, the countries of your users, or the products that sold best, where a chart would be too much.

  • It is plain HTML and CSS, a list with no client code and no measuring, so it works in Server Components and renders the same on the server.
  • It sorts the rows for you, biggest first by default, and can show only the first few.
  • Two looks: the bar behind the row, or a thin bar under it. Three sizes, and colors from the theme in light and dark.
  • Rows can be links, with the whole row as the target, and can have an icon, a rank, and the share of the total.
  • Long names are cut short with an ellipsis. The bars grow in one after the other, and not for people who prefer reduced motion.
  • The bar only decorates and is hidden from screen readers: the name and the number are text, so the list reads as it looks.

For a real chart with axes, see BarChart. Bar List is for a short ranking of names.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add tailwind-variants tailwind-merge clsx

# pnpm
pnpm add tailwind-variants tailwind-merge clsx

# npm
npm install tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports. It also uses Link, and the bar-chart animations and chart colors from globals.css.

1. Add the styles

src/types/bar-list-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for BarList. Every item is a name, a number and a bar whose length is
// the number. The bar's color is set on the item as `--bar`, so the classes
// below can mix it with the background. The class names are written out in
// full so Tailwind can find them.
export const barListStyles = tv({
  slots: {
    root: "m-0 flex list-none flex-col p-0",
    item: "relative flex min-w-0",
    row: "flex min-w-0 flex-1 items-center justify-between gap-3",
    track: "",
    bar: "bar-chart-grow-x origin-left",
    name: "flex min-w-0 flex-1 items-center gap-2",
    label: "truncate",
    icon: "shrink-0 text-muted-fg [&_svg]:size-4",
    rank: "w-5 shrink-0 text-xs tabular-nums text-muted-fg",
    value: "shrink-0 font-medium tabular-nums",
    percent: "shrink-0 text-xs tabular-nums text-muted-fg",
    empty: "py-6 text-center text-sm text-muted-fg",
  },
  variants: {
    // `filled`: the bar is the background of the row, behind the name and the
    // number. `line`: name and number on top, a thin bar under them.
    variant: {
      filled: {
        root: "gap-1.5",
        item: "items-center rounded-md px-3",
        track: "absolute inset-0 overflow-hidden rounded-md",
        bar: "h-full rounded-md bg-[color-mix(in_oklab,var(--bar)_28%,transparent)]",
        row: "relative z-10 -mx-3 self-stretch px-3",
      },
      line: {
        root: "gap-4",
        item: "flex-col gap-1.5",
        row: "w-full flex-none",
        track: "order-last h-1.5 w-full overflow-hidden rounded-full bg-muted",
        bar: "h-full rounded-full bg-(--bar)",
      },
    },
    size: {
      sm: {},
      md: {},
      lg: {},
    },
  },
  compoundVariants: [
    { variant: "filled", size: "sm", class: { item: "h-7 text-xs" } },
    { variant: "filled", size: "md", class: { item: "h-9 text-sm" } },
    { variant: "filled", size: "lg", class: { item: "h-11 text-base" } },
    { variant: "line", size: "sm", class: { item: "text-xs" } },
    { variant: "line", size: "md", class: { item: "text-sm" } },
    { variant: "line", size: "lg", class: { item: "text-base" } },
  ],
  defaultVariants: { variant: "filled", size: "md" },
});

2. Add the Bar List file

src/components/ui/bar-list/bar-list.tsxShow code
import type { CSSProperties, ReactNode } from "react";
import { Link } from "@/components/ui/link/link";
import { cn } from "@/lib/cn";
import { barListStyles } from "@/types/bar-list-styles";

export interface BarListItem {
  /** What the bar is for: a page, a country, a product. */
  name: string;
  /** The number. The length of the bar follows it. */
  value: number;
  /** Makes the name a link, and the whole row clickable. A link to another site opens in a new tab. */
  href?: string;
  /** Something before the name, such as an icon or a flag. */
  icon?: ReactNode;
  /** The color of this bar, any CSS color. Defaults to the `color` of the list. */
  color?: string;
}

export interface BarListProps {
  /** The rows: a name and a number each. */
  data: BarListItem[];
  /** The order of the rows: biggest first, smallest first, or as they are given. Defaults to `descending`. */
  sortOrder?: "descending" | "ascending" | "none";
  /**
   * What the longest bar stands for. Defaults to the biggest number, so the top
   * bar is full. Set it to compare against a goal or a total.
   */
  maxValue?: number;
  /** The bar behind the row (`filled`) or a thin bar under it (`line`). Defaults to `filled`. */
  variant?: "filled" | "line";
  size?: "sm" | "md" | "lg";
  /** The color of the bars, any CSS color. Defaults to the first chart color of the theme. */
  color?: string;
  /** Where a number is shown: `(v) => "$" + v`. */
  valueFormatter?: (value: number) => string;
  /** The share of the total, in percent, after each number. Defaults to `false`. */
  showPercent?: boolean;
  /** A number before each name, from 1. Defaults to `false`. */
  showRank?: boolean;
  /** Only the first this many rows, after sorting. */
  limit?: number;
  /** What it says with no rows. Defaults to "No data". */
  emptyText?: string;
  /** Names the list for screen readers. */
  "aria-label"?: string;
  className?: string;
}

const defaultValueFormatter = (value: number) =>
  new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(value);

const percentFormatter = new Intl.NumberFormat("en-US", {
  maximumFractionDigits: 1,
});

/**
 * A list of things with a bar for each: the pages that got the most visits,
 * the countries of your users, the products that sold best. The bar is as long
 * as the number, so the list can be read at a glance and compared.
 *
 * It is plain HTML and CSS, a list with no client code, so it works in Server
 * Components and needs no measuring. It sorts the rows for you, can link each
 * one, and takes its colors from the theme.
 *
 * @example
 * <BarList
 *   aria-label="Top pages"
 *   data={[
 *     { name: "/home", value: 456 },
 *     { name: "/pricing", value: 351 },
 *   ]}
 * />
 */
export function BarList({
  data,
  sortOrder = "descending",
  maxValue,
  variant,
  size,
  color = "var(--chart-1)",
  valueFormatter = defaultValueFormatter,
  showPercent = false,
  showRank = false,
  limit,
  emptyText = "No data",
  "aria-label": ariaLabel,
  className,
}: BarListProps) {
  const styles = barListStyles({ variant, size });

  const sorted =
    sortOrder === "none"
      ? [...data]
      : [...data].sort((a, b) =>
          sortOrder === "ascending" ? a.value - b.value : b.value - a.value,
        );
  const rows = limit === undefined ? sorted : sorted.slice(0, limit);
  const total = data.reduce((sum, item) => sum + Math.max(item.value, 0), 0);
  const max = maxValue ?? Math.max(0, ...data.map((item) => item.value));

  if (data.length === 0) {
    return <p className={cn(styles.empty(), className)}>{emptyText}</p>;
  }

  return (
    <ul aria-label={ariaLabel} className={cn(styles.root(), className)}>
      {rows.map((item, i) => {
        const width =
          max > 0 ? Math.min(Math.max(item.value / max, 0), 1) * 100 : 0;
        const share = total > 0 ? (Math.max(item.value, 0) / total) * 100 : 0;
        const label = <span className={styles.label()}>{item.name}</span>;

        return (
          <li
            key={item.name}
            className={styles.item()}
            style={{ "--bar": item.color ?? color } as CSSProperties}
          >
            <div aria-hidden="true" className={styles.track()}>
              <div
                className={styles.bar()}
                style={{ width: `${width}%`, animationDelay: `${i * 40}ms` }}
              />
            </div>
            <div className={styles.row()}>
              <div className={styles.name()}>
                {showRank ? (
                  <span className={styles.rank()}>{i + 1}</span>
                ) : null}
                {item.icon ? (
                  <span aria-hidden="true" className={styles.icon()}>
                    {item.icon}
                  </span>
                ) : null}
                {item.href ? (
                  <Link
                    href={item.href}
                    variant="hover"
                    className="min-w-0 truncate font-medium text-fg no-underline after:absolute after:inset-0 after:content-['']"
                  >
                    {item.name}
                  </Link>
                ) : (
                  label
                )}
              </div>
              <span className={styles.value()}>
                {valueFormatter(item.value)}
                {showPercent ? (
                  <>
                    {" "}
                    <span className={cn(styles.percent(), "ml-1.5")}>
                      {percentFormatter.format(share)}%
                    </span>
                  </>
                ) : null}
              </span>
            </div>
          </li>
        );
      })}
    </ul>
  );
}

3. Use it

import { BarList } from "@/components/ui/bar-list/bar-list";

Anatomy

A list, and in each row a bar, a name and a number.

<BarList
  aria-label="Top pages"
  data={[
    { name: "/home", value: 456 },
    { name: "/pricing", value: 351 },
  ]}
/>
PartRendered asNotes
ListulOne row for each item, in the order you choose.
Bardiv, aria-hiddenAs long as the number, out of the biggest one or of maxValue. It only decorates: the name and the number are text.
Namespan, or a linkCut short with an ellipsis when it is too long. With href it is a link, and the whole row is its target.
NumberspanWritten by valueFormatter, with the share of the total beside it if you ask.

Examples

Usage

  • /home
    456
  • /pricing
    351
  • /docs
    271
  • /blog
    191
  • /about
    91

Sorting

Biggest first by default. Sort the other way, or keep the rows in the order you give them.

  • /about
    91
  • /blog
    191
  • /docs
    271
  • /pricing
    351
  • /home
    456
  • /blog
    191
  • /home
    456
  • /about
    91
  • /pricing
    351

Variants

The bar can be the background of the row, or a thin line under the name and the number.

  • /home
    456
  • /pricing
    351
  • /docs
    271
  • /home
    456
  • /pricing
    351
  • /docs
    271

Sizes

  • /home
    456
  • /pricing
    351
  • /home
    456
  • /pricing
    351
  • /home
    456
  • /pricing
    351

Colors

Set color on the list for every bar, or on an item for its own bar, with any CSS color or a theme token.

  • /home
    456
  • /pricing
    351
  • /docs
    271
  • Passed
    128
  • Skipped
    24
  • Failed
    9

Icons

Something before the name: an icon, a flag, an avatar.

  • Home
    456
  • Guides
    351
  • Components
    271
  • Newsletter
    191
  • GitHub
    91

Rank, percent and limit

showRank numbers the rows, showPercent adds each row's share of the total, and limit keeps only the first few after sorting.

  • 1/home
    456 33.5%
  • 2/pricing
    351 25.8%
  • 3/docs
    271 19.9%
  • 4/blog
    191 14%
  • 5/about
    91 6.7%
  • /home
    456
  • /pricing
    351
  • /docs
    271

Formatting values

valueFormatter writes the numbers, for money, units or time.

  • Pro plan
    $48,200
  • Team plan
    $31,750
  • Add-ons
    $12,400

Against a goal

By default the biggest number fills its bar. Set maxValue to measure every bar against a goal or a total instead.

  • /home
    456
  • /pricing
    351
  • /docs
    271

No data

With no rows it says so.

No visits yet

Component API

BarList takes the props below, and each item of data takes the second table.

PropTypeDefault
dataBarListItem[]-
sortOrder"descending" | "ascending" | "none""descending"
maxValuenumberthe biggest value
variant"filled" | "line""filled"
size"sm" | "md" | "lg""md"
colorstring"var(--chart-1)"
valueFormatter(value: number) => stringnumber with grouping
showPercentbooleanfalse
showRankbooleanfalse
limitnumber-
emptyTextstring"No data"
aria-labelstring-
classNamestring-

BarListItem

PropTypeDefault
namestring-
valuenumber-
hrefstring-
iconReactNode-
colorstringthe color of the list