Skip to content
Thrum

Sidebar

The side navigation of an application: labelled groups of links, a header, a footer, and a toggle that folds it to a rail of icons. Use it when an app has more destinations than fit in a top bar. For a handful of links use the navbar; for the headings of one page use the table of contents.

Install

npx shadcn@latest add https://thrumui.dev/r/sidebar.json

Adds components/ui/sidebar.tsx. Nothing else in your project changes.

import { Sidebar } from "@/components/ui/sidebar";

Automatically installs icons chevron-down and panel-left from the icon set.

Props

PropTypeDefaultDescription
Sidebar: collapsedboolean–Whether it is a rail of icons, when the parent holds the state. Use it with onCollapsedChange, and store it yourself if it should survive a reload: the sidebar writes no cookie and no storage.
Sidebar: defaultCollapsedbooleanDefault falseWhether it starts as a rail, when the sidebar holds its own state.
Sidebar: onCollapsedChange(collapsed: boolean) => void–Called with the new state when the toggle or the shortcut changes it.
Sidebar: shortcutstring–A letter that toggles the sidebar together with Ctrl, or ⌘ on a Mac: "b" gives Ctrl + B. There is no shortcut unless you set one, and it is ignored while a text field has the focus.
Sidebar: soundbooleanDefault truePlay a rising pair of clicks when it expands and a falling pair when it collapses, if the visitor has sound on.
Sidebar: classNamestring–Extra classes for the aside element. w-64 data-collapsed:w-14 changes the two widths; the defaults are 224 and 48 pixels.
Sidebar: ...propsComponentProps<"aside">–Every other attribute. Give it an aria-label.
SidebarHeader, SidebarFooterComponentProps<"div">–The fixed rows at the top and the bottom. Hide what does not fit the rail with group-data-collapsed/sidebar:hidden.
SidebarContentComponentProps<"nav">–The part between them. It scrolls when the groups are taller than the sidebar. Give it an aria-label.
SidebarGroup: labelstring–The group's heading. In the rail it is kept for screen readers only.
SidebarGroup: collapsiblebooleanDefault falseLet the reader fold the group by pressing its label. It needs a label. The rail shows every group open.
SidebarGroup: defaultOpenbooleanDefault trueWhether a collapsible group starts open.
SidebarItem: hrefstring–Where the item leads. With it the item is a link; without it, a button that takes onClick.
SidebarItem: iconReactNode–An inline SVG, drawn at 16 pixels. In the rail it is all that shows; an item without one shows the first letter of its label there.
SidebarItem: badgeReactNode–A count or a short word at the end of the row. Hidden in the rail, but still read by screen readers.
SidebarItem: activebooleanDefault falseThis item is the page being shown. It gets aria-current="page", a fill, a heavier label and a bar at its edge.
SidebarItem: disabledbooleanDefault falseDimmed and cannot be pressed. A disabled item is always a button.
SidebarItem: ...propsHTMLAttributes<HTMLElement>–Every attribute a link and a button share: onClick, title, aria attributes. In the rail, title defaults to the label, so the browser shows it as a tooltip.
SidebarToggleComponentProps<"button">–The button that switches between the sidebar and the rail. It works anywhere inside the Sidebar. Children replace its icon.

Motion and sound

Motion

  • The sidebar's width changes between 224 and 48 pixels over 200 ms. The page beside it follows, so give that a min-width of 0.
  • Labels and badges leave and return at once, at the start of the change.
  • An item's background and text colour change over 150 ms on hover. A collapsible group's chevron turns over 150 ms; its items show and hide at once.
  • Reduced motion: the width, the colours and the chevron change at once.

Sound

  • Two rising clicks when the sidebar expands, two falling clicks when it collapses to the rail, by the toggle or by the shortcut.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • The sidebar is an aside landmark and its content a nav landmark: name both with aria-label. Each group holds a list of links or buttons.
  • The toggle is a button named Toggle sidebar with aria-expanded and aria-controls pointing at the sidebar.
  • A collapsible group is a native details element: its label is the summary, which browsers and screen readers already treat as a button with a state.
  • In the rail the labels and badges stay in the page for screen readers, and each item's title shows its label as the browser's own tooltip.
  • The current item is marked with aria-current="page", a fill, a heavier label and a 2 pixel bar, so it does not rest on colour alone.
  • A long label is cut with an ellipsis. Under a glass material the sidebar is translucent, and its tint keeps the text at 4.5 to 1 over any page.
KeysAction
TabMove through the toggle, the group labels that fold, and the items, from top to bottom.
Enter / SpaceOn the toggle: collapse to the rail or expand. On a group label: fold or unfold the group. On an item: follow or press it.
Ctrl + letter / ⌘ letterToggle the sidebar from anywhere on the page, when shortcut is set.

Source

components/ui/sidebar.tsx
"use client";

import { createContext, useContext, useEffect, useId, useState, type ComponentProps, type HTMLAttributes, type ReactNode } from "react";

import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { ChevronDownIcon } from "@/components/icons/chevron-down";
import { PanelLeftIcon } from "@/components/icons/panel-left";

type SidebarState = { collapsed: boolean; toggle: () => void; id: string };
const SidebarContext = createContext<SidebarState>({ collapsed: false, toggle: () => {}, id: "" });

const FOCUS = "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";

export type SidebarProps = ComponentProps<"aside"> & {
  /** Whether it is a rail of icons, when the parent holds the state. Use with `onCollapsedChange`. */
  collapsed?: boolean;
  /** Whether it starts as a rail, when the sidebar holds its own state. */
  defaultCollapsed?: boolean;
  /** Called with the new state when the toggle or the shortcut changes it. */
  onCollapsedChange?: (collapsed: boolean) => void;
  /** A letter that toggles the sidebar together with Ctrl, or ⌘ on a Mac. No shortcut unless you set one. Example: `"b"`. */
  shortcut?: string;
  /** Play a rising pair of clicks when it expands and a falling pair when it collapses, if the visitor has sound on. */
  sound?: boolean;
};

/**
 * An application sidebar: 224 pixels wide, or a 48 pixel rail of icons. Build it from the parts below.
 * It fills the height of its parent and keeps nothing between visits: hold `collapsed` yourself to remember it.
 * It is a panel surface, so it turns to glass when the page's material asks for it. Name it with an `aria-label`.
 */
export function Sidebar({ collapsed, defaultCollapsed = false, onCollapsedChange, shortcut, sound = true, id, className, ...props }: SidebarProps) {
  const [inner, setInner] = useState(defaultCollapsed);
  const own = useId();
  const rail = collapsed ?? inner;
  const toggle = () => {
    setInner(!rail);
    onCollapsedChange?.(!rail);
    if (sound) play(rail ? "toggleOn" : "toggleOff");
  };

  // Subscribed again after every render, so the handler always toggles from the current state.
  useEffect(() => {
    if (!shortcut) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key.toLowerCase() !== shortcut.toLowerCase() || !(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey || event.repeat) return;
      // In a text field the same keys belong to the field.
      const field = event.target instanceof HTMLElement && (event.target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(event.target.tagName));
      if (field) return;
      event.preventDefault();
      toggle();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  });

  return (
    <SidebarContext.Provider value={{ collapsed: rail, toggle, id: id ?? own }}>
      <aside
        id={id ?? own}
        data-slot="sidebar"
        data-surface="panel"
        data-collapsed={rail || undefined}
        className={cn(
          "group/sidebar flex h-full w-56 flex-none flex-col overflow-hidden border-e bg-card text-card-foreground data-collapsed:w-12",
          "transition-[width] duration-200 ease-out motion-reduce:transition-none",
          className,
        )}
        {...props}
      />
    </SidebarContext.Provider>
  );
}

/** The top row: a brand, a workspace switch, the toggle. In the rail its content is centred. */
export function SidebarHeader({ className, ...props }: ComponentProps<"div">) {
  return <div data-slot="sidebar-header" className={cn("flex h-12 flex-none items-center gap-2 border-b px-2 group-data-collapsed/sidebar:justify-center", className)} {...props} />;
}

/** The part that scrolls: a `<nav>` that holds the groups. Name it with an `aria-label`. */
export function SidebarContent({ className, ...props }: ComponentProps<"nav">) {
  return <nav data-slot="sidebar-content" className={cn("flex min-h-0 flex-auto flex-col gap-4 overflow-x-hidden overflow-y-auto p-2", className)} {...props} />;
}

/** The bottom row: an account, a status, a link to help. In the rail its content is centred. */
export function SidebarFooter({ className, ...props }: ComponentProps<"div">) {
  return <div data-slot="sidebar-footer" className={cn("flex flex-none items-center gap-2 border-t p-2 group-data-collapsed/sidebar:justify-center", className)} {...props} />;
}

export type SidebarGroupProps = {
  /** The group's heading. In the rail it is kept for screen readers only. */
  label?: string;
  /** Let the reader fold the group by pressing its label. Needs a `label`. */
  collapsible?: boolean;
  /** Whether a collapsible group starts open. */
  defaultOpen?: boolean;
  className?: string;
  /** `SidebarItem` elements. */
  children?: ReactNode;
};

const GROUP_LABEL = "flex h-7 items-center gap-2 px-2 text-xs font-medium text-muted-foreground";

/**
 * A list of items under an optional label. A collapsible group is a native `<details>`, so its label is the button
 * that folds it. The rail shows every group open: an icon that is folded away could not be reached.
 */
export function SidebarGroup({ label, collapsible = false, defaultOpen = true, className, children }: SidebarGroupProps) {
  const { collapsed } = useContext(SidebarContext);
  const [open, setOpen] = useState(defaultOpen);
  const labelId = useId();
  const list = (
    // A column of stretched rows, not a grid: a grid track would grow to the longest label instead of cutting it.
    <ul data-slot="sidebar-group-list" className="flex flex-col gap-0.5">
      {children}
    </ul>
  );
  if (collapsible && label && !collapsed) {
    return (
      <details data-slot="sidebar-group" open={open} onToggle={(event) => setOpen(event.currentTarget.open)} className={cn("group/sidebar-group", className)}>
        <summary className={cn(GROUP_LABEL, "mb-0.5 cursor-pointer list-none justify-between rounded-md select-none hover:text-foreground [&::-webkit-details-marker]:hidden", FOCUS)}>
          <span className="truncate">{label}</span>
          <ChevronDownIcon size={14} className="flex-none transition-[rotate] duration-150 ease-out group-open/sidebar-group:rotate-180 motion-reduce:transition-none" />
        </summary>
        {list}
      </details>
    );
  }
  return (
    <div data-slot="sidebar-group" role="group" aria-labelledby={label ? labelId : undefined} className={className}>
      {label && (
        <div id={labelId} className={cn(GROUP_LABEL, "mb-0.5", collapsed && "sr-only")}>
          <span className="truncate">{label}</span>
        </div>
      )}
      {list}
    </div>
  );
}

export type SidebarItemProps = HTMLAttributes<HTMLElement> & {
  /** Where the item leads. With it the item is a link; without it, a button. */
  href?: string;
  /** An inline SVG, drawn at 16 pixels. In the rail it is all that shows; an item without one shows its first letter there. */
  icon?: ReactNode;
  /** A count or a short word at the end of the row. Hidden in the rail, but still read by screen readers. */
  badge?: ReactNode;
  /** This item is the page being shown. It is marked with `aria-current="page"`. */
  active?: boolean;
  /** Dimmed and cannot be pressed. A disabled item is always a button. */
  disabled?: boolean;
};

/** One row of a `SidebarGroup`: a link or a button with an icon, a label and a badge. A long label is cut. */
export function SidebarItem({ href, icon, badge, active = false, disabled = false, title, className, children, ...props }: SidebarItemProps) {
  const { collapsed } = useContext(SidebarContext);
  const text = typeof children === "string" ? children : undefined;
  const mark = icon ?? (collapsed ? text?.slice(0, 1) : null);
  const shared = {
    "data-slot": "sidebar-item",
    // The rail has no room for the label, so the browser's own tooltip carries it.
    title: title ?? (collapsed ? text : undefined),
    "aria-current": active ? ("page" as const) : undefined,
    className: cn(
      "group/sidebar-item relative flex h-8 w-full min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 text-sm whitespace-nowrap",
      "transition-[background-color,color] duration-150 ease-out hover:bg-accent hover:text-accent-foreground motion-reduce:transition-none",
      "disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent disabled:hover:text-card-foreground",
      // The current page: a fill, a heavier label and a bar at the edge, so it never rests on colour alone.
      "aria-[current=page]:bg-accent aria-[current=page]:font-medium aria-[current=page]:text-accent-foreground",
      "aria-[current=page]:before:absolute aria-[current=page]:before:inset-y-1.5 aria-[current=page]:before:start-0 aria-[current=page]:before:w-0.5 aria-[current=page]:before:rounded-[calc(var(--radius)*9999)] aria-[current=page]:before:bg-primary",
      "group-data-collapsed/sidebar:justify-center group-data-collapsed/sidebar:px-0",
      FOCUS,
      className,
    ),
    ...props,
  };
  const body = (
    <>
      {mark != null && (
        <span data-slot="sidebar-item-icon" aria-hidden="true" className="grid size-4 flex-none place-items-center font-medium [&>svg]:size-4">
          {mark}
        </span>
      )}
      <span className={cn("min-w-0 flex-auto truncate text-start", collapsed && "sr-only")}>{children}</span>
      {badge != null && (
        <span
          data-slot="sidebar-item-badge"
          className={cn("flex-none text-xs tabular-nums text-muted-foreground group-hover/sidebar-item:text-accent-foreground group-aria-[current=page]/sidebar-item:text-accent-foreground", collapsed && "sr-only")}
        >
          {badge}
        </span>
      )}
    </>
  );
  return (
    <li>
      {href !== undefined && !disabled ? (
        <a href={href} {...shared}>
          {body}
        </a>
      ) : (
        <button type="button" disabled={disabled} {...shared}>
          {body}
        </button>
      )}
    </li>
  );
}

/** The button that switches between the full sidebar and the rail. Place it anywhere inside the `Sidebar`. */
export function SidebarToggle({ className, onClick, children, ...props }: ComponentProps<"button">) {
  const { collapsed, toggle, id } = useContext(SidebarContext);
  return (
    <button
      type="button"
      data-slot="sidebar-toggle"
      aria-label="Toggle sidebar"
      aria-expanded={!collapsed}
      aria-controls={id}
      onClick={(event) => {
        onClick?.(event);
        if (!event.defaultPrevented) toggle();
      }}
      className={cn(
        "grid size-8 flex-none cursor-pointer place-items-center rounded-md text-muted-foreground transition-[background-color,color] duration-150 ease-out hover:bg-accent hover:text-accent-foreground motion-reduce:transition-none",
        FOCUS,
        className,
      )}
      {...props}
    >
      {children ?? (
        <PanelLeftIcon size={16} className="rtl:-scale-x-100" />
      )}
    </button>
  );
}

Files and dependencies

Adds
components/ui/sidebar.tsx
Packages
None
Brings along
Sound engine
Icons
chevron-downpanel-left

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor