Skip to content
2k
On This Page

Sidebar

A composable, themeable and customizable sidebar component.

A sidebar that collapses to icons.

Sidebars are one of the most complex components to build. They are central to any application and often contain a lot of moving parts.

We now have a solid foundation to build on top of. Composable. Themeable. Customizable.

Browse the Blocks Library.

Installation

pnpm dlx solidui-cli@latest add sidebar

Install the required Solid UI dependencies:

pnpm dlx solidui-cli@latest add button input separator sheet skeleton tooltip

Copy and paste the following code into your project.

components/ui/sidebar.tsx
// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import {
  dynamic,
  type ComponentProps,
  type JSX,
  type ValidComponent
} from "@solidjs/web"
import { cva, type VariantProps } from "class-variance-authority"
import {
  isStatic,
  createContext,
  createMemo,
  createSignal,
  Match,
  merge,
  omit,
  onSettled,
  Show,
  Switch,
  useContext,
  type Accessor,
  type Component
} from "solid-js"

import { cn } from "~/lib/utils"
import { useIsMobile } from "~/hooks/use-mobile"
import { Button, type ButtonProps } from "~/components/ui/button"
import { Input } from "~/components/ui/input"
import { Separator } from "~/components/ui/separator"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle
} from "~/components/ui/sheet"
import { Skeleton } from "~/components/ui/skeleton"
import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip"

type PolymorphicProps<T extends ValidComponent, P> = Omit<
  P,
  "as" | "class" | "children"
> &
  Omit<
    ComponentProps<T>,
    keyof P | "as" | "class" | "children" | "onChange"
  > & {
    as?: T
    class?: string | undefined
    children?: JSX.Element
  }

const SIDEBAR_COOKIE_NAME = "sidebar_state"

const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7

const SIDEBAR_WIDTH = "16rem"

const SIDEBAR_WIDTH_MOBILE = "18rem"

const SIDEBAR_WIDTH_ICON = "3rem"

const SIDEBAR_KEYBOARD_SHORTCUT = "b"

type SidebarContextProps = {
  state: Accessor<"expanded" | "collapsed">
  open: Accessor<boolean>
  setOpen: (open: boolean | ((value: boolean) => boolean)) => void
  openMobile: Accessor<boolean>
  setOpenMobile: (open: boolean | ((value: boolean) => boolean)) => void
  isMobile: Accessor<boolean>
  toggleSidebar: () => void
}

const SidebarContext = createContext<SidebarContextProps | null>(null)

function useSidebar() {
  const context = useContext(SidebarContext)
  if (!context) {
    throw new Error("useSidebar must be used within a SidebarProvider.")
  }
  return context
}

type SidebarProviderProps = ComponentProps<"div"> & {
  defaultOpen?: boolean
  open?: boolean
  onOpenChange?: (open: boolean) => void
}

const SidebarProvider = (props: SidebarProviderProps) => {
  const local = merge({ defaultOpen: true }, props)
  const others = omit(
    props,
    "defaultOpen",
    "open",
    "onOpenChange",
    "class",
    "style",
    "children"
  )
  const isMobile = useIsMobile()
  const [openMobile, setOpenMobile] = createSignal(false)
  const [_open, _setOpen] = createSignal(local.defaultOpen)
  const open = () => local.open ?? _open()
  const setOpen = (value: boolean | ((value: boolean) => boolean)) => {
    if (local.onOpenChange) {
      local.onOpenChange(typeof value === "function" ? value(open()) : value)
      return
    }
    _setOpen(value)
    document.cookie = `${SIDEBAR_COOKIE_NAME}=${open()}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
  }
  const toggleSidebar = () => {
    return isMobile()
      ? setOpenMobile((isOpen) => !isOpen)
      : setOpen((isOpen) => !isOpen)
  }
  onSettled(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (
        event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
        (event.metaKey || event.ctrlKey)
      ) {
        event.preventDefault()
        toggleSidebar()
      }
    }
    window.addEventListener("keydown", handleKeyDown)
    return () => window.removeEventListener("keydown", handleKeyDown)
  })
  const state = () => (open() ? "expanded" : "collapsed")
  const contextValue: SidebarContextProps = {
    state,
    open,
    setOpen,
    isMobile,
    openMobile,
    setOpenMobile,
    toggleSidebar
  }
  return (
    <SidebarContext value={contextValue}>
      <div
        data-slot="sidebar-wrapper"
        style={{
          "--sidebar-width": SIDEBAR_WIDTH,
          "--sidebar-width-mobile": SIDEBAR_WIDTH_MOBILE,
          "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
          ...(local.style as JSX.CSSProperties)
        }}
        class={cn(
          "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
          local.class
        )}
        {...others}
      >
        {local.children}
      </div>
    </SidebarContext>
  )
}

type SidebarProps = ComponentProps<"div"> & {
  side?: "left" | "right"
  variant?: "sidebar" | "floating" | "inset"
  collapsible?: "offcanvas" | "icon" | "none"
}

const Sidebar: Component<SidebarProps> = (props) => {
  const local = merge<SidebarProps[]>(
    {
      side: "left",
      variant: "sidebar",
      collapsible: "offcanvas"
    },
    props
  )
  const others = omit(
    props,
    "side",
    "variant",
    "collapsible",
    "class",
    "children"
  )
  const mobileContentProps = others as unknown as Omit<
    ComponentProps<typeof SheetContent>,
    "class"
  >
  const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
  return (
    <Switch>
      <Match when={local.collapsible === "none"}>
        <div
          class={cn(
            "flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
            local.class
          )}
          data-slot="sidebar"
          {...others}
        >
          {local.children}
        </div>
      </Match>

      <Match when={isMobile()}>
        <Sheet onOpenChange={setOpenMobile} open={openMobile()}>
          <SheetContent
            class="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
            data-mobile="true"
            data-sidebar="sidebar"
            data-slot="sidebar"
            side={local.side ?? "left"}
            style={{
              "--sidebar-width": "var(--sidebar-width-mobile)"
            }}
            {...mobileContentProps}
          >
            <SheetHeader class="sr-only">
              <SheetTitle>Sidebar</SheetTitle>
              <SheetDescription>Displays the mobile sidebar.</SheetDescription>
            </SheetHeader>
            <div class="flex size-full flex-col">{local.children}</div>
          </SheetContent>
        </Sheet>
      </Match>

      <Match when={!isMobile()}>
        <div
          class="group peer hidden text-sidebar-foreground md:block"
          data-state={state()}
          data-collapsible={state() === "collapsed" ? local.collapsible : ""}
          data-variant={local.variant}
          data-side={local.side}
          data-slot="sidebar"
        >
          <div
            data-slot="sidebar-gap"
            class={cn(
              "transition-[width] duration-200 ease-linear relative w-(--sidebar-width) bg-transparent",
              "group-data-[collapsible=offcanvas]:w-0",
              "group-data-[side=right]:rotate-180",
              local.variant === "floating" || local.variant === "inset"
                ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
                : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
            )}
          />
          <div
            data-slot="sidebar-container"
            class={cn(
              "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
              local.side === "left"
                ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
                : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
              local.variant === "floating" || local.variant === "inset"
                ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
                : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
              local.class
            )}
            {...others}
          >
            <div
              data-sidebar="sidebar"
              data-slot="sidebar-inner"
              class="bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border flex size-full flex-col"
            >
              {local.children}
            </div>
          </div>
        </div>
      </Match>
    </Switch>
  )
}

type SidebarTriggerProps = ButtonProps

const SidebarTrigger = (props: SidebarTriggerProps) => {
  const others = omit(props, "class", "onClick")
  const { toggleSidebar } = useSidebar()
  return (
    <Button
      data-sidebar="trigger"
      data-slot="sidebar-trigger"
      variant="ghost"
      size="icon-sm"
      class={cn("", props.class)}
      onClick={(event: MouseEvent) => {
        // @ts-expect-error - preserves polymorphic trigger handler support
        props.onClick?.(event)
        toggleSidebar()
      }}
      {...others}
    >
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
        class="size-4"
      >
        <rect width="18" height="18" x="3" y="3" rx="2" />
        <path d="M9 3v18" />
      </svg>
      <span class="sr-only">Toggle Sidebar</span>
    </Button>
  )
}

const SidebarRail = (props: ComponentProps<"button">) => {
  const { toggleSidebar } = useSidebar()
  return (
    <button
      data-sidebar="rail"
      data-slot="sidebar-rail"
      aria-label="Toggle Sidebar"
      tabindex={-1}
      onClick={toggleSidebar}
      title="Toggle Sidebar"
      {...props}
      class={cn(
        "hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
        "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
        "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
        "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
        "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
        "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
        props.class
      )}
    />
  )
}

const SidebarInset = (props: ComponentProps<"main">) => (
  <main
    data-slot="sidebar-inset"
    {...props}
    class={cn(
      "bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2 relative flex w-full flex-1 flex-col",
      props.class
    )}
  />
)

const SidebarInput = (props: ComponentProps<typeof Input>) => (
  <Input
    data-slot="sidebar-input"
    data-sidebar="input"
    {...props}
    class={cn("h-8 w-full bg-background shadow-none", props.class)}
  />
)

const SidebarHeader = (props: ComponentProps<"div">) => (
  <div
    data-slot="sidebar-header"
    data-sidebar="header"
    {...props}
    class={cn("gap-2 p-2 flex flex-col", props.class)}
  />
)

const SidebarFooter = (props: ComponentProps<"div">) => (
  <div
    data-slot="sidebar-footer"
    data-sidebar="footer"
    {...props}
    class={cn("gap-2 p-2 flex flex-col", props.class)}
  />
)

type SidebarSeparatorProps = ComponentProps<typeof Separator>

const SidebarSeparator = (props: SidebarSeparatorProps) => (
  <Separator
    data-slot="sidebar-separator"
    data-sidebar="separator"
    {...props}
    class={cn("mx-2 bg-sidebar-border w-auto", props.class)}
  />
)

const SidebarContent = (props: ComponentProps<"div">) => (
  <div
    data-slot="sidebar-content"
    data-sidebar="content"
    {...props}
    class={cn(
      "no-scrollbar gap-0 flex min-h-0 flex-1 flex-col overflow-auto group-data-[collapsible=icon]:overflow-hidden",
      props.class
    )}
  />
)

const SidebarGroup = (props: ComponentProps<"div">) => (
  <div
    data-slot="sidebar-group"
    data-sidebar="group"
    {...props}
    class={cn(
      "p-2 relative flex w-full min-w-0 flex-col",
      props.class
    )}
  />
)

type SidebarGroupLabelProps<T extends ValidComponent = "div"> =
  PolymorphicProps<T, ComponentProps<T>>

const SidebarGroupLabel = <T extends ValidComponent = "div">(
  props: SidebarGroupLabelProps<T>
) => {
  const others = omit(props as SidebarGroupLabelProps, "class", "as")
  const Comp = dynamic(() => props.as ?? "div", {
    static: isStatic(props, "as")
  })
  return (
    <Comp
      data-slot="sidebar-group-label"
      data-sidebar="group-label"
      class={cn(
        "h-8 rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 flex shrink-0 items-center outline-hidden [&>svg]:shrink-0",
        props.class
      )}
      {...others}
    />
  )
}

type SidebarGroupActionProps<T extends ValidComponent = "button"> =
  PolymorphicProps<T, ComponentProps<T>>

const SidebarGroupAction = <T extends ValidComponent = "button">(
  props: SidebarGroupActionProps<T>
) => {
  const others = omit(props as SidebarGroupActionProps, "class", "as")
  const Comp = dynamic(() => props.as ?? "button", {
    static: isStatic(props, "as")
  })
  return (
    <Comp
      data-slot="sidebar-group-action"
      data-sidebar="group-action"
      class={cn(
        "absolute top-3.5 right-3 w-5 rounded-md p-0 text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 flex aspect-square items-center justify-center outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 md:after:hidden [&>svg]:shrink-0",
        props.class
      )}
      {...others}
    />
  )
}

const SidebarGroupContent = (props: ComponentProps<"div">) => (
  <div
    data-slot="sidebar-group-content"
    data-sidebar="group-content"
    {...props}
    class={cn("text-sm w-full", props.class)}
  />
)

const SidebarMenu = (props: ComponentProps<"ul">) => (
  <ul
    data-slot="sidebar-menu"
    data-sidebar="menu"
    {...props}
    class={cn("gap-0 flex w-full min-w-0 flex-col", props.class)}
  />
)

const SidebarMenuItem = (props: ComponentProps<"li">) => (
  <li
    data-slot="sidebar-menu-item"
    data-sidebar="menu-item"
    {...props}
    class={cn("group/menu-item relative", props.class)}
  />
)

const sidebarMenuButtonVariants = cva(
  "peer/menu-button gap-2 rounded-md p-2 text-left text-sm ring-sidebar-ring transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground flex w-full items-center overflow-hidden outline-hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",
  {
    variants: {
      variant: {
        default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
        outline: "bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]"
      },
      size: {
        default: "h-8 text-sm",
        sm: "h-7 text-xs",
        lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!"
      }
    },
    defaultVariants: {
      variant: "default",
      size: "default"
    }
  }
)

type SidebarMenuButtonProps<T extends ValidComponent = "button"> =
  PolymorphicProps<T, Pick<ComponentProps<T>, "class" | "children">> &
    VariantProps<typeof sidebarMenuButtonVariants> & {
      isActive?: boolean
      tooltip?: string
    }

const SidebarMenuButton = <T extends ValidComponent = "button">(
  rawProps: SidebarMenuButtonProps<T>
) => {
  const local = merge(
    { isActive: false, variant: "default", size: "default" },
    rawProps
  ) as SidebarMenuButtonProps
  const others = omit(
    rawProps as SidebarMenuButtonProps,
    "isActive",
    "tooltip",
    "as",
    "variant",
    "size",
    "class"
  )
  const { isMobile, state } = useSidebar()
  const Comp = dynamic(() => local.as ?? "button", {
    static: isStatic(rawProps, "as")
  })
  const MenuButton = (menuButtonProps: SidebarMenuButtonProps) => {
    const forwardedProps = omit(menuButtonProps, "class", "as")
    return (
      <Comp
        data-slot="sidebar-menu-button"
        data-sidebar="menu-button"
        data-size={local.size}
        data-active={local.isActive}
        class={cn(
          sidebarMenuButtonVariants({
            variant: local.variant,
            size: local.size
          }),
          menuButtonProps.class,
          local.class
        )}
        {...forwardedProps}
        {...others}
      />
    )
  }
  return (
    <Show fallback={<MenuButton />} when={local.tooltip}>
      <Tooltip>
        <TooltipTrigger render={MenuButton} class="w-full" />
        <TooltipContent
          side="right"
          align="center"
          hidden={state() !== "collapsed" || isMobile()}
        >
          {local.tooltip}
        </TooltipContent>
      </Tooltip>
    </Show>
  )
}

type SidebarMenuActionProps<T extends ValidComponent = "button"> =
  ComponentProps<T> & {
    showOnHover?: boolean
  }

const SidebarMenuAction = <T extends ValidComponent = "button">(
  rawProps: PolymorphicProps<T, SidebarMenuActionProps>
) => {
  const local = merge(
    { showOnHover: false },
    rawProps
  ) as SidebarMenuActionProps
  const others = omit(
    rawProps as PolymorphicProps<"button", SidebarMenuActionProps>,
    "class",
    "as",
    "showOnHover"
  )
  const Comp = dynamic(() => rawProps.as ?? "button", {
    static: isStatic(rawProps, "as")
  })
  return (
    <Comp
      data-slot="sidebar-menu-action"
      data-sidebar="menu-action"
      class={cn(
        "absolute top-1.5 right-1 aspect-square w-5 rounded-md p-0 text-sidebar-foreground ring-sidebar-ring peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 flex items-center justify-center outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 md:after:hidden [&>svg]:shrink-0",
        local.showOnHover &&
          "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground md:opacity-0 data-open:opacity-100",
        local.class
      )}
      {...others}
    />
  )
}

const SidebarMenuBadge: Component<ComponentProps<"div">> = (props) => (
  <div
    data-slot="sidebar-menu-badge"
    data-sidebar="menu-badge"
    {...props}
    class={cn(
      "pointer-events-none absolute right-1 flex h-5 min-w-5 rounded-md px-1 text-xs font-medium text-sidebar-foreground peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 peer-data-active/menu-button:text-sidebar-accent-foreground flex items-center justify-center tabular-nums select-none group-data-[collapsible=icon]:hidden",
      props.class
    )}
  />
)

type SidebarMenuSkeletonProps = ComponentProps<"div"> & {
  showIcon?: boolean
}

const SidebarMenuSkeleton: Component<SidebarMenuSkeletonProps> = (rawProps) => {
  const local = merge({ showIcon: false }, rawProps)
  const others = omit(rawProps, "class", "showIcon")
  const width = createMemo(() => `${Math.floor(Math.random() * 40) + 50}%`)
  return (
    <div
      data-slot="sidebar-menu-skeleton"
      data-sidebar="menu-skeleton"
      class={cn("h-8 gap-2 rounded-md px-2 flex items-center", local.class)}
      {...others}
    >
      <Show when={local.showIcon}>
        <Skeleton
          class="size-4 rounded-md"
          data-sidebar="menu-skeleton-icon"
        />
      </Show>
      <Skeleton
        class="h-4 max-w-(--skeleton-width) flex-1"
        data-sidebar="menu-skeleton-text"
        style={{
          "--skeleton-width": width()
        }}
      />
    </div>
  )
}

const SidebarMenuSub: Component<ComponentProps<"ul">> = (props) => (
  <ul
    data-slot="sidebar-menu-sub"
    data-sidebar="menu-sub"
    {...props}
    class={cn("mx-3.5 translate-x-px gap-1 border-l border-sidebar-border px-2.5 py-0.5 group-data-[collapsible=icon]:hidden flex min-w-0 flex-col", props.class)}
  />
)

const SidebarMenuSubItem: Component<ComponentProps<"li">> = (props) => (
  <li
    data-slot="sidebar-menu-sub-item"
    data-sidebar="menu-sub-item"
    {...props}
    class={cn("group/menu-sub-item relative", props.class)}
  />
)

type SidebarMenuSubButtonProps<T extends ValidComponent = "a"> =
  ComponentProps<T> & {
    size?: "sm" | "md"
    isActive?: boolean
  }

const SidebarMenuSubButton = <T extends ValidComponent = "a">(
  rawProps: PolymorphicProps<T, SidebarMenuSubButtonProps>
) => {
  const local = merge({ size: "md" }, rawProps) as SidebarMenuSubButtonProps
  const others = omit(
    rawProps as PolymorphicProps<"a", SidebarMenuSubButtonProps>,
    "size",
    "isActive",
    "class",
    "as"
  )
  const Comp = dynamic(() => rawProps.as ?? "a", {
    static: isStatic(rawProps, "as")
  })
  return (
    <Comp
      data-slot="sidebar-menu-sub-button"
      data-sidebar="menu-sub-button"
      data-size={local.size}
      data-active={local.isActive}
      class={cn(
        "h-7 gap-2 rounded-md px-2 text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground data-[size=md]:text-sm data-[size=sm]:text-xs data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:text-sidebar-accent-foreground flex min-w-0 -translate-x-px items-center overflow-hidden outline-hidden group-data-[collapsible=icon]:hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:shrink-0",
        local.class
      )}
      {...others}
    />
  )
}

export {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupAction,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInput,
  SidebarInset,
  SidebarMenu,
  SidebarMenuAction,
  SidebarMenuBadge,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSkeleton,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  SidebarProvider,
  SidebarRail,
  SidebarSeparator,
  SidebarTrigger,
  useSidebar,
  type SidebarProps
}

Update the import paths to match your project setup.

Usage

app/layout.tsx
import { AppSidebar } from "~/components/app-sidebar"
import { SidebarProvider, SidebarTrigger } from "~/components/ui/sidebar"
 
export default function Layout(props: { children: any }) {
  return (
    <SidebarProvider>
      <AppSidebar />
      <main>
        <SidebarTrigger />
        {props.children}
      </main>
    </SidebarProvider>
  )
}
components/app-sidebar.tsx
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarHeader
} from "~/components/ui/sidebar"
 
export function AppSidebar() {
  return (
    <Sidebar>
      <SidebarHeader />
      <SidebarContent>
        <SidebarGroup />
        <SidebarGroup />
      </SidebarContent>
      <SidebarFooter />
    </Sidebar>
  )
}

Composition

Use the following composition to build a Sidebar layout:

SidebarProvider
โ”œโ”€โ”€ Sidebar
โ”‚   โ”œโ”€โ”€ SidebarHeader
โ”‚   โ”œโ”€โ”€ SidebarContent
โ”‚   โ”‚   โ”œโ”€โ”€ SidebarGroup
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ SidebarGroupLabel
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ SidebarGroupAction
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ SidebarGroupContent
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ SidebarMenu
โ”‚   โ”‚   โ”‚       โ”œโ”€โ”€ SidebarMenuItem
โ”‚   โ”‚   โ”‚       โ”‚   โ”œโ”€โ”€ SidebarMenuButton
โ”‚   โ”‚   โ”‚       โ”‚   โ”œโ”€โ”€ SidebarMenuAction
โ”‚   โ”‚   โ”‚       โ”‚   โ””โ”€โ”€ SidebarMenuBadge
โ”‚   โ”‚   โ”‚       โ””โ”€โ”€ SidebarMenuItem
โ”‚   โ”‚   โ”‚           โ”œโ”€โ”€ SidebarMenuButton
โ”‚   โ”‚   โ”‚           โ””โ”€โ”€ SidebarMenuSub
โ”‚   โ”‚   โ”‚               โ”œโ”€โ”€ SidebarMenuSubItem
โ”‚   โ”‚   โ”‚               โ””โ”€โ”€ SidebarMenuSubItem
โ”‚   โ”‚   โ””โ”€โ”€ SidebarGroup
โ”‚   โ”‚       โ””โ”€โ”€ SidebarMenu
โ”‚   โ”‚           โ”œโ”€โ”€ SidebarMenuItem
โ”‚   โ”‚           โ””โ”€โ”€ SidebarMenuItem
โ”‚   โ”œโ”€โ”€ SidebarFooter
โ”‚   โ””โ”€โ”€ SidebarRail
โ”œโ”€โ”€ SidebarInset
โ””โ”€โ”€ SidebarTrigger

Structure

A Sidebar component is composed of the following parts:

  • SidebarProvider handles collapsible state.
  • Sidebar is the sidebar container.
  • SidebarHeader and SidebarFooter stay at the top and bottom of the sidebar.
  • SidebarContent is the scrollable content area.
  • SidebarGroup defines a section inside SidebarContent.
  • SidebarTrigger toggles the sidebar.
Sidebar structure

SidebarProvider

Wrap your app in SidebarProvider so Sidebar, SidebarTrigger, and useSidebar can share the same open state.

Props

NameTypeDescription
defaultOpenbooleanDefault open state of the sidebar.
openbooleanOpen state of the sidebar (controlled).
onOpenChange(open: boolean) => voidSets open state of the sidebar (controlled).

Width

If you have a single sidebar in your app, update the width constants inside sidebar.tsx:

components/ui/sidebar.tsx
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"

If you need to override widths per layout, use CSS variables on SidebarProvider:

<SidebarProvider
  style={{
    "--sidebar-width": "20rem",
    "--sidebar-width-mobile": "20rem"
  }}
>
  <Sidebar />
</SidebarProvider>

Keyboard Shortcut

Use Cmd+B on macOS or Ctrl+B on Windows and Linux to toggle the sidebar.

components/ui/sidebar.tsx
const SIDEBAR_KEYBOARD_SHORTCUT = "b"

The main Sidebar component renders the responsive, collapsible sidebar shell.

Props

PropertyTypeDescription
side"left" | "right"The side of the sidebar.
variant"sidebar" | "floating" | "inset"The visual variant of the sidebar.
collapsible"offcanvas" | "icon" | "none"The collapsible behavior.
PropDescription
offcanvasA collapsible sidebar that slides in from the left or right.
iconA sidebar that collapses to icons.
noneA non-collapsible sidebar.

Note: If you use the inset variant, wrap your page content in SidebarInset.

<SidebarProvider>
  <Sidebar variant="inset" />
  <SidebarInset>
    <main>{children}</main>
  </SidebarInset>
</SidebarProvider>

useSidebar

Use useSidebar when you need to read or control the shared sidebar state.

import { useSidebar } from "~/components/ui/sidebar"
 
export function AppSidebar() {
  const {
    state,
    open,
    setOpen,
    openMobile,
    setOpenMobile,
    isMobile,
    toggleSidebar
  } = useSidebar()
}
PropertyTypeDescription
stateAccessor<"expanded" | "collapsed">The current desktop visual state.
openAccessor<boolean>Whether the desktop sidebar is open.
setOpen(open: boolean | updater) => voidSets the desktop open state.
openMobileAccessor<boolean>Whether the mobile sidebar is open.
setOpenMobile(open: boolean | updater) => voidSets the mobile open state.
isMobileAccessor<boolean>Whether the current layout is mobile.
toggleSidebar() => voidToggles desktop or mobile sidebar state

SidebarHeader

Use SidebarHeader to add a sticky header region to the sidebar.

components/app-sidebar.tsx
<Sidebar>
  <SidebarHeader>
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger
            render={(partProps) => <SidebarMenuButton {...partProps} />}
            class=""
          >
            Select Workspace
            <ChevronDownIcon class="ml-auto" />
          </DropdownMenuTrigger>
          <DropdownMenuContent class="w-(--anchor-width)">
            <DropdownMenuItem>
              <span>Acme Inc</span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  </SidebarHeader>
</Sidebar>

SidebarFooter

Use SidebarFooter to add a sticky footer region to the sidebar.

<Sidebar>
  <SidebarFooter>
    <SidebarMenu>
      <SidebarMenuItem>
        <SidebarMenuButton>
          <User2Icon /> Username
        </SidebarMenuButton>
      </SidebarMenuItem>
    </SidebarMenu>
  </SidebarFooter>
</Sidebar>

SidebarContent

SidebarContent wraps the scrollable body of the sidebar.

<Sidebar>
  <SidebarContent>
    <SidebarGroup />
    <SidebarGroup />
  </SidebarContent>
</Sidebar>

SidebarGroup

Use SidebarGroup to create a section inside the sidebar.

A SidebarGroup can contain a SidebarGroupLabel, a SidebarGroupContent, and an optional SidebarGroupAction.

<SidebarGroup>
  <SidebarGroupLabel>Application</SidebarGroupLabel>
  <SidebarGroupAction>
    <PlusIcon /> <span class="sr-only">Add Project</span>
  </SidebarGroupAction>
  <SidebarGroupContent />
</SidebarGroup>

To make a SidebarGroup collapsible, wrap it in Collapsible.

<Collapsible defaultOpen>
  <SidebarGroup>
    <CollapsibleTrigger
      render={(partProps) => <SidebarGroupLabel {...partProps} />}
      class="group/collapsible-trigger w-full"
    >
      Help
      <ChevronDownIcon class="ml-auto transition-transform group-data-[expanded]/collapsible-trigger:rotate-180" />
    </CollapsibleTrigger>
    <CollapsibleContent>
      <SidebarGroupContent />
    </CollapsibleContent>
  </SidebarGroup>
</Collapsible>

SidebarMenu

Use SidebarMenu to build menus inside a SidebarGroup.

Sidebar menu
<SidebarMenu>
  {projects.map((project) => (
    <SidebarMenuItem>
      <SidebarMenuButton as="a" href={project.url}>
        <project.icon />
        <span>{project.name}</span>
      </SidebarMenuButton>
    </SidebarMenuItem>
  ))}
</SidebarMenu>

SidebarMenuButton

SidebarMenuButton renders the main interactive control for a menu item.

By default it renders a button, but you can change the underlying element with the as prop.

Use isActive to mark the current route.

<SidebarMenuButton as="a" href="#" isActive>
  Home
</SidebarMenuButton>

SidebarMenuAction

Use SidebarMenuAction for secondary actions aligned to a menu item.

<SidebarMenuItem>
  <SidebarMenuButton as="a" href="#">
    <HomeIcon />
    <span>Home</span>
  </SidebarMenuButton>
  <SidebarMenuAction>
    <PlusIcon /> <span class="sr-only">Add Project</span>
  </SidebarMenuAction>
</SidebarMenuItem>

SidebarMenuSub

Use SidebarMenuSub to render nested items under a menu entry.

<SidebarMenuItem>
  <SidebarMenuButton />
  <SidebarMenuSub>
    <SidebarMenuSubItem>
      <SidebarMenuSubButton as="a" href="#" />
    </SidebarMenuSubItem>
  </SidebarMenuSub>
</SidebarMenuItem>

SidebarMenuBadge

Use SidebarMenuBadge to show counts or status beside a menu item.

<SidebarMenuItem>
  <SidebarMenuButton />
  <SidebarMenuBadge>24</SidebarMenuBadge>
</SidebarMenuItem>

SidebarMenuSkeleton

Use SidebarMenuSkeleton for loading states.

<SidebarMenu>
  <For each={Array.from({ length: 5 })}>
    {() => (
      <SidebarMenuItem>
        <SidebarMenuSkeleton />
      </SidebarMenuItem>
    )}
  </For>
</SidebarMenu>

SidebarTrigger

Use SidebarTrigger to render the default toggle button.

import { useSidebar } from "~/components/ui/sidebar"
 
export function CustomTrigger() {
  const { toggleSidebar } = useSidebar()
 
  return <button onClick={toggleSidebar}>Toggle Sidebar</button>
}

SidebarRail

SidebarRail renders the narrow interactive rail used to toggle the sidebar on desktop.

<Sidebar>
  <SidebarHeader />
  <SidebarContent>
    <SidebarGroup />
  </SidebarContent>
  <SidebarFooter />
  <SidebarRail />
</Sidebar>

Controlled Sidebar

Use open and onOpenChange when you need to control the sidebar externally.

import { createSignal } from "solid-js"
 
export function AppSidebar() {
  const [open, setOpen] = createSignal(false)
 
  return (
    <SidebarProvider open={open()} onOpenChange={setOpen}>
      <Sidebar />
    </SidebarProvider>
  )
}

Theming

Use the following CSS variables to theme the sidebar.

@layer base {
  :root {
    --sidebar: oklch(0.985 0 0);
    --sidebar-foreground: oklch(0.141 0.005 285.823);
    --sidebar-primary: oklch(0.21 0.006 285.885);
    --sidebar-primary-foreground: oklch(0.985 0 0);
    --sidebar-accent: oklch(0.967 0.001 286.375);
    --sidebar-accent-foreground: oklch(0.21 0.006 285.885);
    --sidebar-border: oklch(0.92 0.004 286.32);
    --sidebar-ring: oklch(0.705 0.015 286.067);
  }
 
  .dark {
    --sidebar: oklch(0.21 0.006 285.885);
    --sidebar-foreground: oklch(0.985 0 0);
    --sidebar-primary: oklch(0.92 0.004 286.32);
    --sidebar-primary-foreground: oklch(0.21 0.006 285.885);
    --sidebar-accent: oklch(0.274 0.006 286.033);
    --sidebar-accent-foreground: oklch(0.985 0 0);
    --sidebar-border: oklch(1 0 0 / 10%);
    --sidebar-ring: oklch(0.552 0.016 285.938);
  }
}

Styling

Use data attributes to style the sidebar across different states.

<Sidebar collapsible="icon">
  <SidebarContent>
    <SidebarGroup class="group-data-[collapsible=icon]:hidden" />
  </SidebarContent>
</Sidebar>
<SidebarMenuItem>
  <SidebarMenuButton />
  <SidebarMenuAction class="peer-data-[active=true]/menu-button:opacity-100" />
</SidebarMenuItem>

Changelog