Skip to content
Product block

Collapsible Icon-Rail Sidebar

Folds between a full list and an icon rail without losing any accessible names, with a Ctrl/Cmd+B shortcut and tooltips that show on keyboard focus too.

197 lineslucide-react
  • sidebar
  • collapse
  • rail
  • icons
  • shortcut

What's included

  • components/sidebar-collapsible.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add sidebar-collapsible

Or over MCP, from your editor's agent — no account needed.

License

Free to read, copy and install, for personal and non-commercial projects. Shipping it in client work or a paid product needs Pro ($79 once). The source lands in your repo and stops being ours — no attribution, nothing to upgrade.

Was this useful?

Start a page with this section — add more, order them, and leave with the page source.

Preview

Your page content goes here

Rendered live in your current theme — this is the same component whose source is below, not a screenshot of it.

Source

components/sidebar-collapsible.tsx
'use client'

/**
 * <SidebarCollapsible> — one sidebar that folds between a full-width list and
 * an icon-only rail.
 *
 *  - The toggle carries `aria-expanded` and `aria-controls`, with a label that
 *    never changes. Swapping "Collapse" for "Expand" AND flipping the state
 *    makes a screen reader say the same thing twice, in opposite directions.
 *  - Collapsing must not delete the accessible names. The label switches to
 *    `sr-only` rather than unmounting, so a rail of bare icons is still a list
 *    of named links. Its parent is `relative` because `sr-only` is absolutely
 *    positioned and would otherwise scroll the whole page sideways.
 *  - The tooltip on a collapsed item is `aria-hidden` on purpose: the name is
 *    already in the link, and announcing it twice is noise. It shows on
 *    keyboard focus as well as hover — a tooltip only a mouse can trigger
 *    hides exactly the labels a keyboard user lost.
 *  - Cmd/Ctrl+B toggles it, the shortcut every editor taught people. It is
 *    ignored while typing in a field.
 *  - Width animates only for people who have not asked for reduced motion.
 */

import * as React from 'react'
import {
  Home,
  Inbox,
  CalendarDays,
  BarChart3,
  Settings,
  PanelLeft,
} from 'lucide-react'

export interface CollapsibleItem {
  id: string
  label: string
  icon: React.ReactNode
  badge?: string
}

export interface SidebarCollapsibleProps {
  items?: CollapsibleItem[]
  defaultActiveId?: string
  defaultCollapsed?: boolean
  onCollapsedChange?: (collapsed: boolean) => void
  children?: React.ReactNode
  className?: string
}

const icon = 'h-[18px] w-[18px] shrink-0'

const DEFAULT_ITEMS: CollapsibleItem[] = [
  { id: 'home', label: 'Home', icon: <Home aria-hidden className={icon} /> },
  { id: 'inbox', label: 'Inbox', icon: <Inbox aria-hidden className={icon} />, badge: '4' },
  { id: 'calendar', label: 'Calendar', icon: <CalendarDays aria-hidden className={icon} /> },
  { id: 'reports', label: 'Reports', icon: <BarChart3 aria-hidden className={icon} /> },
  { id: 'settings', label: 'Settings', icon: <Settings aria-hidden className={icon} /> },
]

function isTypingTarget(target: EventTarget | null) {
  if (!(target instanceof HTMLElement)) return false
  return target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)
}

export function SidebarCollapsible({
  items = DEFAULT_ITEMS,
  defaultActiveId = 'inbox',
  defaultCollapsed = false,
  onCollapsedChange,
  children,
  className = '',
}: SidebarCollapsibleProps) {
  const uid = React.useId()
  const [collapsed, setCollapsed] = React.useState(defaultCollapsed)
  const [activeId, setActiveId] = React.useState(defaultActiveId)

  const toggle = React.useCallback(() => {
    setCollapsed((c) => {
      onCollapsedChange?.(!c)
      return !c
    })
  }, [onCollapsedChange])

  React.useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'b' && !isTypingTarget(e.target)) {
        e.preventDefault()
        toggle()
      }
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [toggle])

  return (
    <div
      className={`flex h-[32rem] overflow-hidden rounded-2xl border border-border/60 bg-background ${className}`}
    >
      <aside
        aria-label="Application"
        className={`flex shrink-0 flex-col border-e border-border/60 bg-card/40 motion-safe:transition-[width] motion-safe:duration-200 ${
          collapsed ? 'w-[64px]' : 'w-[240px]'
        }`}
      >
        <div className={`flex h-14 items-center gap-2 px-3 ${collapsed ? 'justify-center' : 'justify-between'}`}>
          {collapsed ? null : (
            <span className="flex min-w-0 items-center gap-2 ps-1">
              <span
                aria-hidden
                className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary text-xs font-bold text-primary-foreground"
              >
                H
              </span>
              <span className="truncate text-sm font-semibold tracking-tight">Harbor</span>
            </span>
          )}
          <button
            type="button"
            onClick={toggle}
            aria-label="Toggle sidebar"
            aria-expanded={!collapsed}
            aria-controls={`${uid}-nav`}
            className="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
          >
            <PanelLeft aria-hidden className="h-4 w-4 rtl:-scale-x-100" />
          </button>
        </div>

        <nav
          id={`${uid}-nav`}
          aria-label="Main"
          className={`flex-1 space-y-1 px-2 py-2 ${collapsed ? 'overflow-visible' : 'overflow-y-auto'}`}
        >
          {items.map((item) => {
            const active = item.id === activeId
            return (
              <a
                key={item.id}
                href="#"
                aria-current={active ? 'page' : undefined}
                onClick={(e) => {
                  e.preventDefault()
                  setActiveId(item.id)
                }}
                className={`group relative flex items-center gap-3 rounded-xl py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
                  collapsed ? 'justify-center px-0' : 'px-3'
                } ${
                  active
                    ? 'bg-primary/10 text-primary'
                    : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                }`}
              >
                {item.icon}
                <span className={collapsed ? 'sr-only' : 'flex-1 truncate'}>
                  {item.label}
                  {collapsed && item.badge ? `, ${item.badge} new` : null}
                </span>
                {item.badge && !collapsed ? (
                  <span className="rounded-full bg-primary px-1.5 py-0.5 text-[11px] font-semibold leading-none text-primary-foreground">
                    {item.badge}
                  </span>
                ) : null}
                {item.badge && collapsed ? (
                  <span
                    aria-hidden
                    className="absolute end-2 top-1.5 h-2 w-2 rounded-full bg-primary ring-2 ring-card border border-transparent"
                  />
                ) : null}
                {collapsed ? (
                  <span
                    aria-hidden
                    className="pointer-events-none absolute start-full z-10 ms-3 whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-xs font-medium text-background opacity-0 shadow-md transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100"
                  >
                    {item.label}
                  </span>
                ) : null}
              </a>
            )
          })}
        </nav>

        <p className={`px-4 pb-4 text-xs text-muted-foreground ${collapsed ? 'sr-only' : ''}`}>
          <kbd className="rounded border border-border/60 px-1.5 font-medium">Ctrl</kbd>{' '}
          <kbd className="rounded border border-border/60 px-1.5 font-medium">B</kbd> to toggle
        </p>
      </aside>

      <main className="hidden min-w-0 flex-1 p-6 sm:block">
        {children ?? (
          <div className="flex min-h-full min-w-0 items-center justify-center break-words rounded-xl border border-dashed border-border/60 p-4 text-center text-sm text-muted-foreground">
            Your page content goes here
          </div>
        )}
      </main>
    </div>
  )
}

Before you paste

  • Styling is Tailwind utility classes on semantic tokens (bg-card, text-muted-foreground) — it inherits your theme instead of overriding it.
  • Install: npm i lucide-react
  • Every prop has a default, so it renders standalone before you wire it up.

Where it goes

Drop it at components/sidebar-collapsible.tsx and import it where you need the section:

import { SidebarCollapsible } from '@/components/sidebar-collapsible'

Customize

2 of this block’s props are simple enough to drive from here. Change them and the block below re-renders — it is the same component whose source is above, not a mock of it. Everything else it accepts is in the table underneath.

Props

Read out of the component’s own type and signature, so this cannot drift from the source below. Every prop has a default — the component renders standalone before you pass it anything.

PropTypeDefault
itemsCollapsibleItem[]DEFAULT_ITEMS
defaultActiveIdstring'inbox'
defaultCollapsedbooleanfalse
onCollapsedChange(collapsed: boolean) => void—
childrenReact.ReactNode—
classNamestring''

Not using React?

The same block rendered once to markup, wrapped as a file your framework compiles. Tailwind classes are framework-agnostic, so the design transfers intact — the behaviour does not.

This block is interactive. The markup below is its initial state with the event handlers stripped — you will need to re-wire the behaviour in your framework.

sidebar-collapsible.html
<!--
  Collapsible Icon-Rail Sidebar — markup from the Hoverlab catalog.

  This is the block rendered once to HTML and wrapped as a component
  file. It is not a port of the React source: the Tailwind classes carry
  the design, which is the part that took the work, and they are the same
  in every framework.

  This block is interactive in React and the handlers are NOT here.
  Buttons, toggles and menus render in their initial state and do
  nothing until you wire them up.
-->
<div class="flex h-[32rem] overflow-hidden rounded-2xl border border-border/60 bg-background ">
  <aside aria-label="Application" class="flex shrink-0 flex-col border-e border-border/60 bg-card/40 motion-safe:transition-[width] motion-safe:duration-200 w-[240px]">
    <div class="flex h-14 items-center gap-2 px-3 justify-between">
      <span class="flex min-w-0 items-center gap-2 ps-1">
        <span aria-hidden="true" class="flex h-7 w-7 items-center justify-center rounded-lg bg-primary text-xs font-bold text-primary-foreground">H</span>
        <span class="truncate text-sm font-semibold tracking-tight">Harbor</span>
      </span>
      <button type="button" aria-label="Toggle sidebar" aria-expanded="true" aria-controls="_R_0_-nav" class="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-panel-left h-4 w-4 rtl:-scale-x-100" aria-hidden="true">
          <rect width="18" height="18" x="3" y="3" rx="2"></rect>
          <path d="M9 3v18"></path>
        </svg>
      </button>
    </div>
    <nav id="_R_0_-nav" aria-label="Main" class="flex-1 space-y-1 px-2 py-2 overflow-y-auto">
      <a href="#" class="group relative flex items-center gap-3 rounded-xl py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary px-3 text-muted-foreground hover:bg-muted hover:text-foreground">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-house h-[18px] w-[18px] shrink-0" aria-hidden="true">
          <path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"></path>
          <path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
        </svg>
        <span class="flex-1 truncate">Home</span>
      </a>
      <a href="#" aria-current="page" class="group relative flex items-center gap-3 rounded-xl py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary px-3 bg-primary/10 text-primary">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-inbox h-[18px] w-[18px] shrink-0" aria-hidden="true">
          <polyline points="22 12 16 12 14 15 10 15 8 12 2 12"></polyline>
          <path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"></path>
        </svg>
        <span class="flex-1 truncate">Inbox</span>
        <span class="rounded-full bg-primary px-1.5 py-0.5 text-[11px] font-semibold leading-none text-primary-foreground">4</span>
      </a>
      <a href="#" class="group relative flex items-center gap-3 rounded-xl py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary px-3 text-muted-foreground hover:bg-muted hover:text-foreground">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-calendar-days h-[18px] w-[18px] shrink-0" aria-hidden="true">
          <path d="M8 2v4"></path>
          <path d="M16 2v4"></path>
          <rect width="18" height="18" x="3" y="4" rx="2"></rect>
          <path d="M3 10h18"></path>
          <path d="M8 14h.01"></path>
          <path d="M12 14h.01"></path>
          <path d="M16 14h.01"></path>
          <path d="M8 18h.01"></path>
          <path d="M12 18h.01"></path>
          <path d="M16 18h.01"></path>
        </svg>
        <span class="flex-1 truncate">Calendar</span>
      </a>
      <a href="#" class="group relative flex items-center gap-3 rounded-xl py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary px-3 text-muted-foreground hover:bg-muted hover:text-foreground">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chart-column h-[18px] w-[18px] shrink-0" aria-hidden="true">
          <path d="M3 3v16a2 2 0 0 0 2 2h16"></path>
          <path d="M18 17V9"></path>
          <path d="M13 17V5"></path>
          <path d="M8 17v-3"></path>
        </svg>
        <span class="flex-1 truncate">Reports</span>
      </a>
      <a href="#" class="group relative flex items-center gap-3 rounded-xl py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary px-3 text-muted-foreground hover:bg-muted hover:text-foreground">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-settings h-[18px] w-[18px] shrink-0" aria-hidden="true">
          <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"></path>
          <circle cx="12" cy="12" r="3"></circle>
        </svg>
        <span class="flex-1 truncate">Settings</span>
      </a>
    </nav>
    <p class="px-4 pb-4 text-xs text-muted-foreground "><kbd class="rounded border border-border/60 px-1.5 font-medium">Ctrl</kbd> <kbd class="rounded border border-border/60 px-1.5 font-medium">B</kbd> to toggle</p>
  </aside>
  <main class="hidden min-w-0 flex-1 p-6 sm:block">
    <div class="flex min-h-full min-w-0 items-center justify-center break-words rounded-xl border border-dashed border-border/60 p-4 text-center text-sm text-muted-foreground">Your page content goes here</div>
  </main>
</div>
  • This is rendered HTML, not a translation of the React source. The Tailwind classes carry the design and work in any framework.
  • It is one frame: the component in its initial state, with no props applied beyond the defaults.
  • This block is interactive in React — toggles, menus or form state. None of that survives here; the markup is the closed/default state and the handlers are gone. Re-wire them in your own framework.
  • Requires Tailwind, and the design tokens the classes reference (bg-card, text-muted-foreground, and so on). The template ZIPs ship a globals.css that defines them.

What each framework gets across the whole catalog — effects convert properly; this rung is markup.

For AI

The component, its props, the design tokens it expects and the command that installs it — as one prompt. Paste it into Claude, Cursor, v0 or ChatGPT and what they build around it will match the rest of the catalog instead of inventing its own system.

See the prompt

10 more blocks in Sidebars

All of them free to read, copy and install — no account, no locked tiles, no watermarked preview. The whole catalog is open, and so are the API and the CLI.

Browse Sidebars

Shipping one commercially

Copying the code is free. Putting it in client work or a paid product is what Pro is for — the licence, not the access.

  • A commercial licence for everything in the catalog
  • Unlimited bundle exports, in Vue, Svelte and Tailwind
  • One payment — no subscription, nothing to renew
Pro — $79 once

More Sidebars blocks

View category
Open the full page for this block

Docs Sidebar With Filter

Version picker, a labelled filter that announces its match count, and sections that vanish rather than leave a heading over an empty list.

Sidebars208 lines1 dep

Chat History Sidebar

Conversations grouped by recency with a per-row pin toggle that announces itself, and a hover control that stays reachable by keyboard and on touch.

Sidebars170 lines1 dep
Open the full page for this block

File Explorer Tree Sidebar

A real ARIA tree with roving focus, arrow-key expand and collapse, type-ahead and one tab stop, drawn flat so a screen reader is told the structure.

Sidebars260 lines1 dep