Skip to content
Product block

Sidebar With Workspace Switcher

A header that opens a real menu of workspaces: arrow keys, Home/End, Escape returning focus to the trigger, and checked state announced as a radio choice.

241 lineslucide-react
  • sidebar
  • workspace
  • switcher
  • menu
  • multi-tenant

What's included

  • components/sidebar-workspace-switcher.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add sidebar-workspace-switcher

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

Acme Inc workspace

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

Source

components/sidebar-workspace-switcher.tsx
'use client'

/**
 * <SidebarWorkspaceSwitcher> — a sidebar whose header opens a menu of
 * workspaces, the way Slack, Linear and Vercel do.
 *
 *  - It is a menu, so it follows the menu keyboard model rather than a pile of
 *    buttons: Down/Up move between choices, Home/End jump, Escape closes AND
 *    returns focus to the trigger (a menu that drops focus on the page body
 *    strands a keyboard user at the top of the document), and Tab leaves it.
 *  - The choices are `menuitemradio` with `aria-checked`, because picking a
 *    workspace is a one-of-many choice and "Acme, checked" is what says which.
 *  - A pointer press outside closes it. Focus moves into the menu only when it
 *    was opened by the user — a menu that is open on first paint (this demo's
 *    default, since a closed switcher is a screenshot of a button) must not
 *    steal focus on load.
 *  - The trigger's `aria-controls` points at a list that is always mounted,
 *    hidden by attribute when shut, so the reference never dangles.
 */

import * as React from 'react'
import { Check, ChevronsUpDown, Plus, LayoutDashboard, FolderKanban, Users } from 'lucide-react'

export interface Workspace {
  id: string
  name: string
  plan: string
}

export interface SidebarWorkspaceSwitcherProps {
  workspaces?: Workspace[]
  defaultWorkspaceId?: string
  defaultOpen?: boolean
  onWorkspaceChange?: (id: string) => void
  children?: React.ReactNode
  className?: string
}

const DEFAULT_WORKSPACES: Workspace[] = [
  { id: 'acme', name: 'Acme Inc', plan: 'Team' },
  { id: 'personal', name: 'Personal', plan: 'Free' },
  { id: 'studio', name: 'Northwind Studio', plan: 'Pro' },
]

const NAV = [
  { label: 'Overview', icon: <LayoutDashboard aria-hidden className="h-4 w-4" /> },
  { label: 'Projects', icon: <FolderKanban aria-hidden className="h-4 w-4" /> },
  { label: 'People', icon: <Users aria-hidden className="h-4 w-4" /> },
]

export function SidebarWorkspaceSwitcher({
  workspaces = DEFAULT_WORKSPACES,
  defaultWorkspaceId = 'acme',
  defaultOpen = true,
  onWorkspaceChange,
  children,
  className = '',
}: SidebarWorkspaceSwitcherProps) {
  const uid = React.useId()
  const [open, setOpen] = React.useState(defaultOpen)
  const [workspaceId, setWorkspaceId] = React.useState(defaultWorkspaceId)
  const triggerRef = React.useRef<HTMLButtonElement>(null)
  const menuRef = React.useRef<HTMLDivElement>(null)
  const rootRef = React.useRef<HTMLElement>(null)
  const openedByUser = React.useRef(false)

  const current = workspaces.find((w) => w.id === workspaceId) ?? workspaces[0]

  const items = () =>
    Array.from(menuRef.current?.querySelectorAll<HTMLElement>('[role^="menuitem"]') ?? [])

  const openMenu = (focus: 'checked' | 'first' | 'last' = 'checked') => {
    openedByUser.current = true
    setOpen(true)
    // Focus after the menu is unhidden; a hidden element cannot take focus.
    requestAnimationFrame(() => {
      const list = items()
      const target =
        focus === 'first'
          ? list[0]
          : focus === 'last'
            ? list[list.length - 1]
            : (list.find((el) => el.getAttribute('aria-checked') === 'true') ?? list[0])
      target?.focus()
    })
  }

  const closeMenu = (returnFocus: boolean) => {
    setOpen(false)
    if (returnFocus) triggerRef.current?.focus()
  }

  React.useEffect(() => {
    if (!open) return
    const onPointerDown = (e: PointerEvent) => {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener('pointerdown', onPointerDown)
    return () => document.removeEventListener('pointerdown', onPointerDown)
  }, [open])

  const onMenuKeyDown = (e: React.KeyboardEvent) => {
    const list = items()
    const i = list.indexOf(document.activeElement as HTMLElement)
    if (e.key === 'ArrowDown') list[(i + 1) % list.length]?.focus()
    else if (e.key === 'ArrowUp') list[(i - 1 + list.length) % list.length]?.focus()
    else if (e.key === 'Home') list[0]?.focus()
    else if (e.key === 'End') list[list.length - 1]?.focus()
    else if (e.key === 'Escape') closeMenu(true)
    else if (e.key === 'Tab') setOpen(false)
    else return
    if (e.key !== 'Tab') e.preventDefault()
  }

  const choose = (id: string) => {
    setWorkspaceId(id)
    onWorkspaceChange?.(id)
    closeMenu(true)
  }

  return (
    <div
      className={`flex h-[32rem] overflow-hidden rounded-2xl border border-border/60 bg-background ${className}`}
    >
      <aside
        ref={rootRef}
        aria-label="Application"
        className="relative flex w-64 shrink-0 flex-col border-e border-border/60 bg-card/40"
      >
        <div className="p-3">
          <button
            ref={triggerRef}
            type="button"
            aria-haspopup="menu"
            aria-expanded={open}
            aria-controls={`${uid}-menu`}
            onClick={() => (open ? closeMenu(false) : openMenu())}
            onKeyDown={(e) => {
              if (e.key === 'ArrowDown') {
                e.preventDefault()
                openMenu('first')
              } else if (e.key === 'ArrowUp') {
                e.preventDefault()
                openMenu('last')
              }
            }}
            className="flex w-full items-center gap-3 rounded-xl border border-border/60 bg-background px-3 py-2 text-start transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
          >
            <span
              aria-hidden
              className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary text-sm font-bold text-primary-foreground"
            >
              {current.name.slice(0, 1)}
            </span>
            <span className="min-w-0 flex-1">
              <span className="block truncate text-sm font-semibold">{current.name}</span>
              <span className="block truncate text-xs text-muted-foreground">{current.plan} plan</span>
            </span>
            <ChevronsUpDown aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />
          </button>
        </div>

        <div
          ref={menuRef}
          id={`${uid}-menu`}
          role="menu"
          aria-label="Workspaces"
          hidden={!open}
          onKeyDown={onMenuKeyDown}
          className="absolute inset-x-3 top-[4.5rem] z-20 rounded-xl border border-border/60 bg-card p-1.5 shadow-xl"
        >
          <p aria-hidden className="truncate px-2.5 pb-1 pt-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
            Workspaces
          </p>
          {workspaces.map((w) => {
            const checked = w.id === workspaceId
            return (
              <button
                key={w.id}
                type="button"
                role="menuitemradio"
                aria-checked={checked}
                tabIndex={-1}
                onClick={() => choose(w.id)}
                className="flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-start text-sm transition-colors hover:bg-muted focus-visible:bg-muted focus-visible:outline-none"
              >
                <span
                  aria-hidden
                  className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-muted text-xs font-bold"
                >
                  {w.name.slice(0, 1)}
                </span>
                <span className="flex-1 truncate">{w.name}</span>
                {checked ? <Check aria-hidden className="h-4 w-4 text-primary" /> : null}
              </button>
            )
          })}
          <div role="separator" className="my-1 h-px bg-border/60" />
          <button
            type="button"
            role="menuitem"
            tabIndex={-1}
            onClick={() => closeMenu(true)}
            className="flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-start text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted focus-visible:outline-none"
          >
            <Plus aria-hidden className="h-4 w-4" />
            Create workspace
          </button>
        </div>

        <nav aria-label="Main" className="flex-1 space-y-0.5 px-3 pb-3">
          {NAV.map((item, i) => (
            <a
              key={item.label}
              href="#"
              aria-current={i === 0 ? 'page' : undefined}
              onClick={(e) => e.preventDefault()}
              className={`flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
                i === 0
                  ? 'bg-primary/10 text-primary'
                  : 'text-muted-foreground hover:bg-muted hover:text-foreground'
              }`}
            >
              {item.icon}
              {item.label}
            </a>
          ))}
        </nav>
      </aside>

      <main className="hidden min-w-0 flex-1 p-6 sm:block">
        {children ?? (
          <div className="flex min-h-full items-center justify-center rounded-xl border border-dashed border-border/60 p-4 text-center text-sm text-muted-foreground">
            <span className="min-w-0 truncate">{current.name} workspace</span>
          </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-workspace-switcher.tsx and import it where you need the section:

import { SidebarWorkspaceSwitcher } from '@/components/sidebar-workspace-switcher'

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
workspacesWorkspace[]DEFAULT_WORKSPACES
defaultWorkspaceIdstring'acme'
defaultOpenbooleantrue
onWorkspaceChange(id: string) => 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-workspace-switcher.html
<!--
  Sidebar With Workspace Switcher — 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="relative flex w-64 shrink-0 flex-col border-e border-border/60 bg-card/40">
    <div class="p-3">
      <button type="button" aria-haspopup="menu" aria-expanded="true" aria-controls="_R_0_-menu" class="flex w-full items-center gap-3 rounded-xl border border-border/60 bg-background px-3 py-2 text-start transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary">
        <span aria-hidden="true" class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary text-sm font-bold text-primary-foreground">A</span>
        <span class="min-w-0 flex-1">
          <span class="block truncate text-sm font-semibold">Acme Inc</span>
          <span class="block truncate text-xs text-muted-foreground">Team plan</span>
        </span>
        <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-chevrons-up-down h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true">
          <path d="m7 15 5 5 5-5"></path>
          <path d="m7 9 5-5 5 5"></path>
        </svg>
      </button>
    </div>
    <div id="_R_0_-menu" role="menu" aria-label="Workspaces" class="absolute inset-x-3 top-[4.5rem] z-20 rounded-xl border border-border/60 bg-card p-1.5 shadow-xl">
      <p aria-hidden="true" class="truncate px-2.5 pb-1 pt-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">Workspaces</p>
      <button type="button" role="menuitemradio" aria-checked="true" tabindex="-1" class="flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-start text-sm transition-colors hover:bg-muted focus-visible:bg-muted focus-visible:outline-none">
        <span aria-hidden="true" class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-muted text-xs font-bold">A</span>
        <span class="flex-1 truncate">Acme Inc</span>
        <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-check h-4 w-4 text-primary" aria-hidden="true">
          <path d="M20 6 9 17l-5-5"></path>
        </svg>
      </button>
      <button type="button" role="menuitemradio" aria-checked="false" tabindex="-1" class="flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-start text-sm transition-colors hover:bg-muted focus-visible:bg-muted focus-visible:outline-none">
        <span aria-hidden="true" class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-muted text-xs font-bold">P</span>
        <span class="flex-1 truncate">Personal</span>
      </button>
      <button type="button" role="menuitemradio" aria-checked="false" tabindex="-1" class="flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-start text-sm transition-colors hover:bg-muted focus-visible:bg-muted focus-visible:outline-none">
        <span aria-hidden="true" class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-muted text-xs font-bold">N</span>
        <span class="flex-1 truncate">Northwind Studio</span>
      </button>
      <div role="separator" class="my-1 h-px bg-border/60"></div>
      <button type="button" role="menuitem" tabindex="-1" class="flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-start text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted focus-visible:outline-none"><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-plus h-4 w-4" aria-hidden="true"><path d="M5 12h14"></path><path d="M12 5v14"></path></svg>Create workspace</button>
    </div>
    <nav aria-label="Main" class="flex-1 space-y-0.5 px-3 pb-3">
      <a href="#" aria-current="page" class="flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary 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-layout-dashboard h-4 w-4" aria-hidden="true"><rect width="7" height="9" x="3" y="3" rx="1"></rect><rect width="7" height="5" x="14" y="3" rx="1"></rect><rect width="7" height="9" x="14" y="12" rx="1"></rect><rect width="7" height="5" x="3" y="16" rx="1"></rect></svg>Overview</a>
      <a href="#" class="flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary 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-folder-kanban h-4 w-4" aria-hidden="true"><path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z"></path><path d="M8 10v4"></path><path d="M12 10v2"></path><path d="M16 10v6"></path></svg>Projects</a>
      <a href="#" class="flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary 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-users h-4 w-4" aria-hidden="true"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path><path d="M16 3.128a4 4 0 0 1 0 7.744"></path><path d="M22 21v-2a4 4 0 0 0-3-3.87"></path><circle cx="9" cy="7" r="4"></circle></svg>People</a>
    </nav>
  </aside>
  <main class="hidden min-w-0 flex-1 p-6 sm:block">
    <div class="flex min-h-full items-center justify-center rounded-xl border border-dashed border-border/60 p-4 text-center text-sm text-muted-foreground">
      <span class="min-w-0 truncate">Acme Inc workspace</span>
    </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