# Sidebar

> A vertical list of navigation links on the page background, with groups, icons, counts and a filled current item.

Docs: https://plumbago.ochotzas.com/components/sidebar

## Installation

```sh
npx plumbago add sidebar
```

This copies `components/ui/sidebar.tsx` into your project, along with `cn`, and installs `@base-ui/react`.

## Usage

```tsx
import { Sidebar, SidebarGroup, SidebarItem, SidebarItemIcon, SidebarItemLabel } from "@/components/ui/sidebar"

<Sidebar aria-label="Casa Verde">
  <SidebarGroup>
    <SidebarItem href="/tonight" active>
      <SidebarItemIcon>
        <Moon />
      </SidebarItemIcon>
      <SidebarItemLabel>Tonight</SidebarItemLabel>
    </SidebarItem>
  </SidebarGroup>
</Sidebar>
```

## Examples

### Preview

```tsx
import { BlurSwap } from "@/lib/blur-swap"
import { Sidebar, SidebarGroup, SidebarItem, SidebarItemIcon, SidebarItemLabel } from "@/components/ui/sidebar"
import { BookOpen, CalendarDays, Moon, Settings, Users } from "lucide-react"
import { useState } from "react"

const views = [
  { id: "tonight", title: "Tonight", icon: Moon, summary: "86 covers booked, 12 tables free after 21:30." },
  { id: "reservations", title: "Reservations", icon: CalendarDays, summary: "41 bookings this week, Saturday is full." },
  { id: "menu", title: "Menu", icon: BookOpen, summary: "24 dishes on the menu, two sold out." },
  { id: "staff", title: "Staff", icon: Users, summary: "Nine people on tonight's rota." },
  { id: "settings", title: "Settings", icon: Settings, summary: "Opening hours, tables and receipts." },
]

export default function SidebarDemo() {
  const [view, setView] = useState(views[0])

  return (
    <div className="grid w-full gap-6 sm:grid-cols-[220px_1fr]">
      <Sidebar aria-label="Casa Verde">
        <SidebarGroup>
          {views.map((item) => (
            <SidebarItem
              key={item.id}
              href={`#${item.id}`}
              active={item === view}
              onClick={(event) => {
                event.preventDefault()
                setView(item)
              }}
            >
              <SidebarItemIcon>
                <item.icon strokeWidth={1.75} aria-hidden="true" />
              </SidebarItemIcon>
              <SidebarItemLabel>{item.title}</SidebarItemLabel>
            </SidebarItem>
          ))}
        </SidebarGroup>
      </Sidebar>
      <main className="rounded-lg bg-surface p-6">
        <h2 className="text-title1 font-bold text-ink">
          <BlurSwap text={view?.title ?? ""} />
        </h2>
        <p className="mt-2 text-body text-ink-2">
          <BlurSwap text={view?.summary ?? ""} className="whitespace-normal [&>*]:whitespace-normal" />
        </p>
      </main>
    </div>
  )
}
```

### With counts

```tsx
import { Sidebar, SidebarGroup, SidebarItem, SidebarItemCount, SidebarItemIcon, SidebarItemLabel } from "@/components/ui/sidebar"
import { BookOpen, CalendarDays, Moon } from "lucide-react"

export default function SidebarWithCounts() {
  return (
    <Sidebar aria-label="Casa Verde" className="w-60">
      <SidebarGroup>
        <SidebarItem href="#tonight" active>
          <SidebarItemIcon>
            <Moon strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Tonight</SidebarItemLabel>
          <SidebarItemCount>86</SidebarItemCount>
        </SidebarItem>
        <SidebarItem href="#reservations">
          <SidebarItemIcon>
            <CalendarDays strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Reservations</SidebarItemLabel>
          <SidebarItemCount>12</SidebarItemCount>
        </SidebarItem>
        <SidebarItem href="#menu">
          <SidebarItemIcon>
            <BookOpen strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Menu</SidebarItemLabel>
          <SidebarItemCount>24</SidebarItemCount>
        </SidebarItem>
      </SidebarGroup>
    </Sidebar>
  )
}
```

### With groups

```tsx
import { Sidebar, SidebarGroup, SidebarGroupLabel, SidebarItem, SidebarItemCount, SidebarItemIcon, SidebarItemLabel } from "@/components/ui/sidebar"
import { BookOpen, CalendarDays, Moon, Settings, Utensils, Wine } from "lucide-react"

export default function SidebarWithGroups() {
  return (
    <Sidebar aria-label="Casa Verde" className="w-60">
      <SidebarGroup>
        <SidebarGroupLabel>Service</SidebarGroupLabel>
        <SidebarItem href="#tonight" active>
          <SidebarItemIcon>
            <Moon strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Tonight</SidebarItemLabel>
          <SidebarItemCount>86</SidebarItemCount>
        </SidebarItem>
        <SidebarItem href="#reservations">
          <SidebarItemIcon>
            <CalendarDays strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Reservations</SidebarItemLabel>
          <SidebarItemCount>12</SidebarItemCount>
        </SidebarItem>
      </SidebarGroup>
      <SidebarGroup>
        <SidebarGroupLabel>Menus</SidebarGroupLabel>
        <SidebarItem href="#lunch">
          <SidebarItemIcon>
            <Utensils strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Lunch menu</SidebarItemLabel>
          <SidebarItemCount>14</SidebarItemCount>
        </SidebarItem>
        <SidebarItem href="#dinner">
          <SidebarItemIcon>
            <BookOpen strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Dinner menu</SidebarItemLabel>
          <SidebarItemCount>24</SidebarItemCount>
        </SidebarItem>
        <SidebarItem href="#wine">
          <SidebarItemIcon>
            <Wine strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Wine list</SidebarItemLabel>
          <SidebarItemCount>38</SidebarItemCount>
        </SidebarItem>
      </SidebarGroup>
      <SidebarGroup>
        <SidebarItem href="#settings">
          <SidebarItemIcon>
            <Settings strokeWidth={1.75} aria-hidden="true" />
          </SidebarItemIcon>
          <SidebarItemLabel>Settings</SidebarItemLabel>
        </SidebarItem>
      </SidebarGroup>
    </Sidebar>
  )
}
```

### Scrolling

```tsx
import { ScrollFade } from "@/components/ui/scroll-fade"
import { Sidebar, SidebarGroup, SidebarGroupLabel, SidebarItem, SidebarItemCount, SidebarItemIcon, SidebarItemLabel } from "@/components/ui/sidebar"
import { BookOpen } from "lucide-react"

const lists = [
  ["Lunch menu", 14],
  ["Dinner menu", 24],
  ["Brunch", 11],
  ["Tasting menu", 7],
  ["Desserts", 9],
  ["Wine list", 38],
  ["Cocktails", 16],
  ["Kids menu", 6],
  ["Set lunch", 5],
  ["Private dining", 12],
  ["Terrace snacks", 8],
  ["Christmas menu", 10],
] as const

export default function SidebarScrolling() {
  return (
    <ScrollFade className="h-72 w-60">
      <Sidebar aria-label="Menus" className="py-3">
        <SidebarGroup>
          <SidebarGroupLabel>Menus</SidebarGroupLabel>
          {lists.map(([name, count], index) => (
            <SidebarItem key={name} href={`#${name}`} active={index === 0}>
              <SidebarItemIcon>
                <BookOpen strokeWidth={1.75} aria-hidden="true" />
              </SidebarItemIcon>
              <SidebarItemLabel>{name}</SidebarItemLabel>
              <SidebarItemCount>{count}</SidebarItemCount>
            </SidebarItem>
          ))}
        </SidebarGroup>
      </Sidebar>
    </ScrollFade>
  )
}
```

### Inside an island

```tsx
import { Island } from "@/components/ui/island"
import { Sidebar, SidebarGroup, SidebarItem, SidebarItemIcon, SidebarItemLabel } from "@/components/ui/sidebar"
import { BookOpen, CalendarDays, Moon } from "lucide-react"

export default function SidebarInsideAnIsland() {
  return (
    <Island className="w-full max-w-xs p-3">
      <Sidebar aria-label="Casa Verde">
        <SidebarGroup>
          <SidebarItem href="#tonight" active>
            <SidebarItemIcon>
              <Moon strokeWidth={1.75} aria-hidden="true" />
            </SidebarItemIcon>
            <SidebarItemLabel>Tonight</SidebarItemLabel>
          </SidebarItem>
          <SidebarItem href="#reservations">
            <SidebarItemIcon>
              <CalendarDays strokeWidth={1.75} aria-hidden="true" />
            </SidebarItemIcon>
            <SidebarItemLabel>Reservations</SidebarItemLabel>
          </SidebarItem>
          <SidebarItem href="#menu">
            <SidebarItemIcon>
              <BookOpen strokeWidth={1.75} aria-hidden="true" />
            </SidebarItemIcon>
            <SidebarItemLabel>Menu</SidebarItemLabel>
          </SidebarItem>
        </SidebarGroup>
      </Sidebar>
    </Island>
  )
}
```

## Built on Base UI

Sidebar wraps these Base UI parts and keeps their props:

- [Merge props](https://base-ui.com/react/utils/merge-props)
- [Use render](https://base-ui.com/react/utils/use-render)

## Source

```tsx
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cn } from "@/lib/cn"
import { type ComponentProps, type CSSProperties, useLayoutEffect, useRef, useState } from "react"

type PartProps<T extends keyof React.JSX.IntrinsicElements = "div"> = Omit<ComponentProps<T>, "className"> & { className?: string }

type PillBox = { top: number; bottom: number; left: number; right: number; direction: "up" | "down" | "none" }

const leading = "var(--pb-dur-spring-fast) var(--pb-spring-fast)"
const trailing = "var(--pb-dur-spring-slow) var(--pb-spring-slow)"

const pillTransition: Record<PillBox["direction"], string | undefined> = {
  none: "none",
  up: `top ${leading}, bottom ${trailing}, left ${leading}, right ${leading}`,
  down: `top ${trailing}, bottom ${leading}, left ${leading}, right ${leading}`,
}

function useSidebarPill() {
  const navRef = useRef<HTMLElement | null>(null)
  const [pill, setPill] = useState<PillBox | null>(null)

  useLayoutEffect(() => {
    const nav = navRef.current
    if (!nav) return
    let previous: PillBox | null = null
    const measure = () => {
      const item = nav.querySelector<HTMLElement>("[data-slot=sidebar-item][aria-current=page]")
      if (!item) {
        previous = null
        setPill(null)
        return
      }
      const navBox = nav.getBoundingClientRect()
      const box = item.getBoundingClientRect()
      const top = box.top - navBox.top
      const next: PillBox = {
        top,
        bottom: navBox.bottom - box.bottom,
        left: box.left - navBox.left,
        right: navBox.right - box.right,
        direction: previous === null ? "none" : top < previous.top ? "up" : top > previous.top ? "down" : "none",
      }
      if (previous && next.direction === "none") next.direction = previous.direction
      previous = next
      setPill(next)
    }
    measure()
    const mutations = new MutationObserver(measure)
    mutations.observe(nav, { subtree: true, attributes: true, attributeFilter: ["aria-current"], childList: true })
    const resize = new ResizeObserver(measure)
    resize.observe(nav)
    return () => {
      mutations.disconnect()
      resize.disconnect()
    }
  }, [])

  return { navRef, pill }
}

export function Sidebar({ className, children, ...props }: PartProps<"nav">) {
  const { navRef, pill } = useSidebarPill()
  const pillStyle: CSSProperties | undefined = pill
    ? { top: pill.top, bottom: pill.bottom, left: pill.left, right: pill.right, transition: pillTransition[pill.direction] }
    : undefined
  return (
    <nav ref={navRef} data-slot="sidebar" data-pill={pill ? "" : undefined} className={cn("relative isolate flex flex-col gap-6", className)} {...props}>
      {pill && (
        <span
          data-slot="sidebar-pill"
          aria-hidden="true"
          className="pointer-events-none absolute -z-10 rounded-md bg-surface motion-reduce:transition-none! in-[.on-surface]:bg-bg"
          style={pillStyle}
        />
      )}
      {children}
    </nav>
  )
}

export function SidebarGroup({ className, ...props }: PartProps<"div">) {
  return <div data-slot="sidebar-group" className={cn("flex flex-col gap-0.5", className)} {...props} />
}

export function SidebarGroupLabel({ className, ...props }: PartProps<"h2">) {
  return <h2 data-slot="sidebar-group-label" className={cn("px-3 pb-1.5 text-footnote font-medium text-ink-2", className)} {...props} />
}

export type SidebarItemProps = Omit<useRender.ComponentProps<"a">, "className"> & {
  active?: boolean
  className?: string
}

export function SidebarItem({ render, active, className, ...props }: SidebarItemProps) {
  const dataAttributes = { "data-slot": "sidebar-item" }
  return useRender({
    defaultTagName: "a",
    render,
    props: mergeProps<"a">(
      {
        ...dataAttributes,
        "aria-current": active ? "page" : undefined,
        className: cn(
          "group/sidebar-item relative flex h-11 w-full shrink-0 cursor-pointer items-center gap-3 rounded-md px-3 text-left text-[15px] text-ink-2 select-none md:h-10",
          "transition-colors duration-fast ease-out hover:not-aria-[current=page]:bg-press hover:text-ink [-webkit-tap-highlight-color:transparent]",
          "aria-[current=page]:bg-surface aria-[current=page]:text-ink in-[.on-surface]:aria-[current=page]:bg-bg [[data-pill]_&]:aria-[current=page]:bg-transparent",
          "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent",
          "md:after:absolute md:after:inset-x-0 md:after:-inset-y-0.5 md:after:content-['']",
          className,
        ),
      },
      props,
    ),
  })
}

export function SidebarItemIcon({ className, ...props }: PartProps<"span">) {
  return <span data-slot="sidebar-item-icon" className={cn("grid size-5 shrink-0 place-items-center [&_svg]:size-5", className)} {...props} />
}

export function SidebarItemLabel({ className, children, ...props }: PartProps<"span">) {
  return (
    <span data-slot="sidebar-item-label" className={cn("grid min-w-0 flex-1", className)} {...props}>
      <span className="col-start-1 row-start-1 truncate group-aria-[current=page]/sidebar-item:font-semibold">{children}</span>
      <span aria-hidden="true" className="invisible col-start-1 row-start-1 truncate font-semibold">
        {children}
      </span>
    </span>
  )
}

export function SidebarItemCount({ className, ...props }: PartProps<"span">) {
  return <span data-slot="sidebar-item-count" className={cn("shrink-0 text-footnote font-medium text-ink-2 tabular-nums", className)} {...props} />
}
```
