Sidebar

A side column that turns into a drawer on narrow screens.

From its breakpoint up (md by default) a sidebar is a column, always open. Below it, it’s a drawer built on ui-sdk’s Drawer, like Sheet: its SidebarTrigger opens it, focus moves into it, the page behind is set aside, and Escape, a tap outside or a swipe closes it. The trigger only shows where the sidebar is a drawer. A SidebarProvider connects them, one sidebar a side; give a second one a wider breakpoint, like xl, so the space between keeps room. Workspace is built from it.

Preview
basic.tsx
import { Sidebar, SidebarProvider, SidebarTrigger } from "~/components/ui/sidebar"
import { Text } from "~/components/ui/text"

const sections = ["Front page", "News", "Sport", "Opinion"]

export default function Example() {
  return (
    <SidebarProvider>
      <div className="flex h-80 w-full overflow-hidden border border-border">
        <Sidebar side="left" size="sm" title="Weekend edition">
          <ul className="grid gap-2xs p-md">
            {sections.map((section) => (
              <li key={section}>
                <a
                  href={`#${section}`}
                  className="flex h-8 items-center rounded-lg px-md hover:bg-muted"
                >
                  <Text render={<span />} size="sm">
                    {section}
                  </Text>
                </a>
              </li>
            ))}
          </ul>
        </Sidebar>
        <div className="flex min-w-0 flex-1 flex-col">
          <div className="flex h-11 items-center gap-sm border-b border-border px-lg">
            <SidebarTrigger side="left" />
            <Text render={<span />} size="sm" weight="medium">
              Front page
            </Text>
          </div>
          <div className="p-lg">
            <Text tone="muted">Narrow the window: the sidebar becomes a drawer.</Text>
          </div>
        </div>
      </div>
    </SidebarProvider>
  )
}

Dependencies

What it's built from and what's built from it in Base, read from the imports in its source.

UsesButtonprimitiveScroll AreaprimitiveSheetTextprimitive
Used byWorkspaceblock
Packages @ui-sdk/core@0.1.0-beta.20@ui-sdk/react@0.1.0-beta.20lucide-react@1.73.0

Installation

Set the project up for Base once first, as Getting started shows. Then add it with the CLI, or by hand.

With the CLI

terminal
npx shadcn@latest add https://design.zepez.dev/r/base/sidebar.json

Manually

Install its packages:

terminal
npm install @ui-sdk/core@0.1.0-beta.20 @ui-sdk/react@0.1.0-beta.20 lucide-react@1.73.0

Add the components it uses first, listed under Dependencies.

Then copy the source:

components/ui/sidebar.tsx
import { DrawerTitle } from "@ui-sdk/react/drawer"
import { PanelLeft, PanelRight } from "lucide-react"
import * as React from "react"

import { Button } from "~/components/ui/button"
import { ScrollArea } from "~/components/ui/scroll-area"
import { Sheet, SheetBackdrop, SheetContent } from "~/components/ui/sheet"
import { textVariants } from "~/components/ui/text"
import { cn } from "~/lib/utils"

/*
 * A side column with a title bar, on the left or the right of a layout. From
 * its breakpoint up it's a column, always open. Below it, it's a drawer that
 * slides in from its side, opened by its `SidebarTrigger`, with the rest of the
 * page set aside: focus moves into it, and Escape, a tap outside or a swipe
 * closes it.
 *
 * <SidebarProvider>
 *   <Sidebar side="left" title="…">…</Sidebar>
 *   <header><SidebarTrigger side="left" />…</header>
 * </SidebarProvider>
 */

type SidebarSide = "left" | "right"

/** Where a sidebar turns from a drawer into a column: Tailwind's md, lg and xl. */
type SidebarBreakpoint = "md" | "lg" | "xl"

const minWidth: Record<SidebarBreakpoint, string> = { md: "48rem", lg: "64rem", xl: "80rem" }

type SidebarState = {
  /** Each side's drawer, open or closed, below its breakpoint. */
  open: Record<SidebarSide, boolean>
  setOpen: (side: SidebarSide, open: boolean) => void
  /** Each side's sidebar's breakpoint, or null with none there: its trigger shows below it. */
  present: Record<SidebarSide, SidebarBreakpoint | null>
  register: (side: SidebarSide, breakpoint: SidebarBreakpoint) => () => void
}

const SidebarContext = React.createContext<SidebarState | null>(null)

function useSidebars(): SidebarState {
  const sidebars = React.useContext(SidebarContext)
  if (sidebars === null) throw new Error("Sidebar parts must be inside a <SidebarProvider>")
  return sidebars
}

/** Whether the screen is at least a breakpoint wide; null until the page knows, as on the server. */
function useWide(breakpoint: SidebarBreakpoint): boolean | null {
  const query = `(width >= ${minWidth[breakpoint]})`
  return React.useSyncExternalStore<boolean | null>(
    (onChange) => {
      const list = window.matchMedia(query)
      list.addEventListener("change", onChange)
      return () => list.removeEventListener("change", onChange)
    },
    () => window.matchMedia(query).matches,
    () => null,
  )
}

const closed: Record<SidebarSide, boolean> = { left: false, right: false }
const absent: Record<SidebarSide, SidebarBreakpoint | null> = { left: null, right: null }

/** Connects sidebars to their triggers. Holds up to one sidebar a side. */
function SidebarProvider({ children }: { children?: React.ReactNode }) {
  const [open, setOpens] = React.useState(closed)
  const [present, setPresent] = React.useState(absent)
  // Stable, so a sidebar's effect that registers it doesn't rerun when the registry changes.
  const register = React.useCallback((side: SidebarSide, breakpoint: SidebarBreakpoint) => {
    setPresent((current) => ({ ...current, [side]: breakpoint }))
    return () => setPresent((current) => ({ ...current, [side]: null }))
  }, [])
  const setOpen = React.useCallback((side: SidebarSide, next: boolean) => {
    setOpens((current) => (current[side] === next ? current : { ...current, [side]: next }))
  }, [])
  const value = React.useMemo<SidebarState>(
    () => ({ open, setOpen, present, register }),
    [open, setOpen, present, register],
  )
  return <SidebarContext value={value}>{children}</SidebarContext>
}

type SidebarProps = Omit<React.ComponentProps<"aside">, "title"> & {
  side: SidebarSide
  /** The sidebar's name, in its title bar. */
  title: React.ReactNode
  /** Controls at the end of the title bar. */
  actions?: React.ReactNode
  /** Its width: 16, 18 or 20rem. */
  size?: "sm" | "md" | "lg"
  /**
   * Where it becomes a column: md, lg or xl. Give a second sidebar a wider one, so the space
   * between keeps room.
   */
  breakpoint?: SidebarBreakpoint
}

/** A column from its breakpoint up, and below it a drawer its `SidebarTrigger` opens. */
function Sidebar({
  side,
  title,
  actions,
  size = "lg",
  breakpoint = "md",
  className,
  children,
  ...props
}: SidebarProps) {
  const { open, setOpen, register } = useSidebars()
  React.useEffect(() => register(side, breakpoint), [register, side, breakpoint])
  const wide = useWide(breakpoint)
  // A drawer left open doesn't come back by itself after the screen has been wide.
  React.useEffect(() => {
    if (wide === true) setOpen(side, false)
  }, [wide, setOpen, side])

  if (wide === false) {
    return (
      <Sheet side={side} open={open[side]} onOpenChange={(next) => setOpen(side, next)}>
        <SheetBackdrop />
        <SheetContent
          data-slot="sidebar"
          data-side={side}
          className="w-auto gap-0 border-border bg-background text-foreground data-[side=left]:w-auto data-[side=right]:w-auto sm:data-[side=left]:max-w-none sm:data-[side=right]:max-w-none"
        >
          <SidebarBody
            size={size}
            title={
              <DrawerTitle className={textVariants({ size: "sm", weight: "medium" })}>
                {title}
              </DrawerTitle>
            }
            actions={actions}
          >
            {children}
          </SidebarBody>
        </SheetContent>
      </Sheet>
    )
  }

  // A column, also on the server and until the page knows its width: hidden by CSS below the
  // breakpoint, so a wide screen never waits for it.
  return (
    <aside
      data-slot="sidebar"
      data-side={side}
      data-breakpoint={breakpoint}
      className={cn(
        "hidden shrink-0 flex-col border-border bg-background data-[side=left]:border-r data-[side=right]:border-l",
        "data-[breakpoint=md]:md:flex data-[breakpoint=lg]:lg:flex data-[breakpoint=xl]:xl:flex",
        className,
      )}
      {...props}
    >
      <SidebarBody
        size={size}
        title={<h2 className={textVariants({ size: "sm", weight: "medium" })}>{title}</h2>}
        actions={actions}
      >
        {children}
      </SidebarBody>
    </aside>
  )
}

/** The title bar and the scrolling content, the same in the column and the drawer. */
function SidebarBody({
  size,
  title,
  actions,
  children,
}: {
  size: NonNullable<SidebarProps["size"]>
  title: React.ReactNode
  actions: React.ReactNode
  children: React.ReactNode
}) {
  return (
    <div
      data-size={size}
      className="flex h-full min-h-0 w-80 flex-col data-[size=md]:w-72 data-[size=sm]:w-64"
    >
      <div className="flex h-11 shrink-0 items-center gap-sm border-b border-border px-xl [&>:first-child]:min-w-0 [&>:first-child]:flex-1 [&>:first-child]:truncate">
        {title}
        {actions}
      </div>
      <ScrollArea className="min-h-0 flex-1">{children}</ScrollArea>
    </div>
  )
}

/**
 * Opens a sidebar's drawer. Shows only below the sidebar's breakpoint, where it's a drawer, and
 * not at all with no sidebar on that side.
 */
function SidebarTrigger({
  side,
  className,
  ...props
}: Omit<React.ComponentProps<typeof Button>, "children" | "onClick"> & { side: SidebarSide }) {
  const { open, setOpen, present } = useSidebars()
  const breakpoint = present[side]
  if (breakpoint === null) return null
  return (
    <Button
      variant="ghost"
      size="icon-sm"
      aria-label={`Open the ${side} sidebar`}
      aria-haspopup="dialog"
      aria-expanded={open[side]}
      data-breakpoint={breakpoint}
      onClick={() => setOpen(side, true)}
      // A disclosure, not a menu trigger: don't shade it while expanded, as Button does.
      className={cn(
        "text-muted-foreground hover:text-foreground aria-expanded:bg-transparent hover:aria-expanded:bg-muted",
        "data-[breakpoint=md]:md:hidden data-[breakpoint=lg]:lg:hidden data-[breakpoint=xl]:xl:hidden",
        className,
      )}
      {...props}
    >
      {side === "left" ? <PanelLeft /> : <PanelRight />}
    </Button>
  )
}

export { Sidebar, SidebarProvider, SidebarTrigger }
export type { SidebarBreakpoint, SidebarProps, SidebarSide }

API reference

Generated from Base's types. Props marked ours are added here; the rest come from the ui-sdk part it wraps. Every part also accepts its element's native attributes.

Sidebar

A column from its breakpoint up, and below it a drawer its SidebarTrigger opens.

actionsours

Controls at the end of the title bar.

Type ReactNode

breakpointours

Where it becomes a column: md, lg or xl. Give a second sidebar a wider one, so the space between keeps room.

Type SidebarBreakpoint · Default md

side*ours

Type SidebarSide

sizeours

Its width: 16, 18 or 20rem.

Type "sm" | "md" | "lg" · Default lg

title*ours

The sidebar's name, in its title bar.

Type ReactNode

SidebarProvider

Connects sidebars to their triggers. Holds up to one sidebar a side.

Takes the props of a native div.

SidebarTrigger

Opens a sidebar's drawer. Shows only below the sidebar's breakpoint, where it's a drawer, and not at all with no sidebar on that side.

side*ours

Type SidebarSide

sizeours

Height and padding. The icon sizes are square, for a button holding only an icon.

Type NonNullable<"xs" | "sm" | "md" | "lg" | "icon-xs" | "icon-sm" | "icon" | "icon-lg">

variantours

How much the button stands out. destructive is a tint, for actions that can't be undone.

Type NonNullable<"primary" | "destructive" | "secondary" | "outline" | "ghost" | "link">

className

Class names, or a function of the part's state that returns them.

Type string | ((state: ButtonState) => string)

debug

Logs every state change with its reason to the console, in development builds.

Type boolean

disabled

Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless focusableWhenDisabled is set.

Type boolean · Default false

focusableWhenDisabled

Keeps a disabled button in the tab order with aria-disabled instead of the native attribute, so it can hold focus while it becomes disabled and host a tooltip that says why. Presses still do nothing.

Type boolean · Default false

pendingAnnouncement

What screen readers hear once the button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.

Type string · Default "Loading"

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<ButtonState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: ButtonState) => CSSProperties)

type

What a native button does in a form: "submit" submits it and "reset" resets it. Ignored when the button renders as something else.

Type "button" | "submit" | "reset" · Default "button"

SidebarBreakpoint

Where a sidebar turns from a drawer into a column: Tailwind's md, lg and xl.

Takes the props of a native div.