PC03▸🧭 Navigation · 導航▸側欄
Sidebar Nav
側邊導航
難度 ★★★★★標籤 sidebar · collapse · active3 min read
模式簡述
Sidebar Nav:左側持續可見的主導航。可摺疊成 icon-only 節省空間。dashboard 必備。
Claude Code Prompt
參考:PC03 sidebar-nav 組件:SidebarNav.tsx Sidebar Nav:左側持續可見的主導航。可摺疊成 icon-only 節省空間。dashboard 必備。 限制: - collapse 後 icon 沒 tooltip - active state 太弱 - 手機版直接隱藏
完整程式碼
"use client";
import { useEffect, useState } from "react";
import {
Home,
Folder,
Settings,
ChevronDown,
ChevronRight,
FileText,
} from "lucide-react";
import { cn } from "@/lib/utils";
type State = "expanded" | "collapsed" | "nested";
export function SidebarNav({ state = "expanded" }: { state?: State }) {
const [open, setOpen] = useState(state === "nested");
useEffect(() => setOpen(state === "nested"), [state]);
const compact = state === "collapsed";
return (
<aside
className={cn(
"rounded-lg border border-border bg-background/30 p-2 transition-all",
compact ? "w-14" : "w-56",
)}
>
<ul className="space-y-1">
<li>
<a
className={cn(
"flex items-center gap-2.5 rounded-md bg-lab-accent/10 px-2.5 py-1.5 text-xs text-lab-accent",
compact && "justify-center px-0",
)}
>
<Home className="h-4 w-4 shrink-0" />
{!compact && <span>儀表板</span>}
</a>
</li>
<li>
<button
onClick={() => setOpen((o) => !o)}
className={cn(
"flex w-full items-center gap-2.5 rounded-md px-2.5 py-1.5 text-xs hover:bg-background/60",
compact && "justify-center px-0",
)}
>
<Folder className="h-4 w-4 shrink-0" />
{!compact && (
<>
<span className="flex-1 text-left">專案</span>
{open ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
</>
)}
</button>
{open && !compact && (
<ul className="ml-3 mt-1 space-y-0.5 border-l border-border pl-3">
{["Frontend Lab", "Patterns", "Effects"].map((s) => (
<li key={s}>
<a className="flex items-center gap-2 rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-background/60 hover:text-foreground">
<FileText className="h-3 w-3" />
{s}
</a>
</li>
))}
</ul>
)}
</li>
<li>
<a
className={cn(
"flex items-center gap-2.5 rounded-md px-2.5 py-1.5 text-xs hover:bg-background/60",
compact && "justify-center px-0",
)}
>
<Settings className="h-4 w-4 shrink-0" />
{!compact && <span>設定</span>}
</a>
</li>
</ul>
</aside>
);
}何時用
- ✅ 管理後台、SaaS 主介面
- ✅ 需要快速跨區塊切換
- ✅ 層級兩層內的網站
何時別用
- ❌ marketing site(用 top nav)
- ❌ 手機優先(用 bottom tab bar)
- ❌ 內容主導的閱讀型網站(sidebar 搶注意力)
我踩過的坑
-
collapse 後 icon 沒 tooltip:滑過 icon 應該秀名稱。
-
active state 太弱:當前頁要清楚標出,bg-accent + 左側 1px accent bar。
-
手機版直接隱藏:改成 drawer,但 menu icon 要在頂部明顯位置。
相關模式
- PB02
- PC07