Why Developers Love the Shadcn Sidebar Component

November 4, 2024 (3w ago)

Navigation is a crucial part of any web application. It helps users understand the structure of the application and navigate through it easily. This is why developers often spend a lot of time designing and implementing navigation components. It also means that there are many libraries and frameworks available to help developers build navigation components quickly and easily.

One such library is Shadcn, a collection of React components that help developers build beautiful and functional web applications. They recently released the new Shadcn Sidebar component, that has been getting a lot of attention from developers. In this article, we will take a closer look at the Shadcn Sidebar component and why developers love it.

Why Sidebars Matter

Sidebars are a common navigation pattern in web applications. They are typically used to display navigation links, menus, or other content that is not part of the main content area. Sidebars can help users quickly access different parts of the application, switch between different views, or perform common actions. They are especially useful in applications with a lot of content or complex navigation structures.

They also help solve a psychological problem known as the Hick's Law. Hick's Law states that the time it takes for a person to make a decision is directly proportional to the number of choices they have. By organizing the navigation links into a sidebar, developers can reduce the number of choices presented to the user at any given time, making it easier for them to make decisions and navigate through the application.

Introducing the Shadcn Sidebar Component

Shadcn recently released a new Sidebar component that aims to simplify the process of building sidebars in React applications. The component is designed to be easy to use, highly customizable, and composable, making it suitable for a wide range of applications. Here are some of the reasons why developers love the Shadcn Sidebar component:

Composable Design

The Shadcn Sidebar component is designed to be composable, meaning you can easily assemble it using its various parts. These include:

This modular approach allows you to create a sidebar that fits your specific needs without unnecessary complexity.

Customizability

Customization is at the heart of the Shadcn Sidebar. You can tailor it to your application’s style and functionality requirements with ease. The component supports various props, allowing you to adjust its appearance and behavior:

Theming Support

The Shadcn Sidebar component offers extensive theming capabilities. You can define different color schemes using CSS variables, ensuring your sidebar matches your application's aesthetic. The component supports both light and dark themes, which can be easily switched based on user preference or system settings.

Persistent State

One standout feature is the Sidebar’s ability to maintain its state across page reloads. Using cookies, the component remembers whether the sidebar is open or closed, providing a consistent user experience. This is particularly useful in applications where maintaining state is crucial for usability.

Let's build it, shall we?

Structure

A Sidebar component is composed of the following parts:

Shadcn Sidebar Structure

Installation

npx shadcn@latest add sidebar

The command above should install the colors for you. If not, copy and paste the following in your CSS file.

@layer base {
  :root {
    --sidebar-background: 0 0% 98%;
    --sidebar-foreground: 240 5.3% 26.1%;
    --sidebar-primary: 240 5.9% 10%;
    --sidebar-primary-foreground: 0 0% 98%;
    --sidebar-accent: 240 4.8% 95.9%;
    --sidebar-accent-foreground: 240 5.9% 10%;
    --sidebar-border: 220 13% 91%;
    --sidebar-ring: 217.2 91.2% 59.8%;
  }
 
  .dark {
    --sidebar-background: 240 5.9% 10%;
    --sidebar-foreground: 240 4.8% 95.9%;
    --sidebar-primary: 224.3 76.3% 48%;
    --sidebar-primary-foreground: 0 0% 100%;
    --sidebar-accent: 240 3.7% 15.9%;
    --sidebar-accent-foreground: 240 4.8% 95.9%;
    --sidebar-border: 240 3.7% 15.9%;
    --sidebar-ring: 217.2 91.2% 59.8%;
  }
}

Usage

First, wrap your application in the SidebarProvider and include a SidebarTrigger for toggling:

import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { AppSidebar } from "@/components/app-sidebar";
 
export default function Layout({ children }) {
  return (
    <SidebarProvider>
      <AppSidebar />
      <main>
        <SidebarTrigger />
        {children}
      </main>
    </SidebarProvider>
  );
}

Next, define the sidebar structure in components/app-sidebar.tsx:

import { Sidebar, SidebarContent } from "@/components/ui/sidebar"
 
export function AppSidebar() {
  return (
    <Sidebar>
      <SidebarContent />
    </Sidebar>
  )
}

Customization

Adding the Menu

Let's add a SidebarMenu to the sidebar. We'll use the SidebarMenu component in a SidebarGroup.

import { Calendar, Home, Inbox, Search, Settings } from "lucide-react"
 
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from "@/components/ui/sidebar"
 
// Menu items.
const items = [
  {
    title: "Home",
    url: "#",
    icon: Home,
  },
  {
    title: "Inbox",
    url: "#",
    icon: Inbox,
  },
  {
    title: "Calendar",
    url: "#",
    icon: Calendar,
  },
  {
    title: "Search",
    url: "#",
    icon: Search,
  },
  {
    title: "Settings",
    url: "#",
    icon: Settings,
  },
]
 
export function AppSidebar() {
  return (
    <Sidebar>
      <SidebarContent>
        <SidebarGroup>
          <SidebarGroupLabel>Application</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              {items.map((item) => (
                <SidebarMenuItem key={item.title}>
                  <SidebarMenuButton asChild>
                    <a href={item.url}>
                      <item.icon />
                      <span>{item.title}</span>
                    </a>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>
    </Sidebar>
  )
}

Components

The components in sidebar.tsx are built to be composable i.e you build your sidebar by putting the provided components together. They also compose well with other shadcn/ui components such as DropdownMenu, Collapsible or Dialog etc.

Sidebar Position

You can position the sidebar on the left or right side of the screen by setting the side prop on the Sidebar component. The default value is left.

<Sidebar side="left" /> // Sidebar on the left
<Sidebar side="right" /> // Sidebar on the right

Variants and Collapsibility

Adjust the style and collapsibility of the sidebar using the variant and collapsible props:

<Sidebar variant="floating" collapsible="icon" />

Note: If you use the inset variant, remember to wrap your main content in a SidebarInset component.

Theming with CSS Variables

The variable names used to style the Sidebar are:

@layer base {
  :root {
    --sidebar-background: 0 0% 98%;
    --sidebar-foreground: 240 5.3% 26.1%;
    --sidebar-primary: 240 5.9% 10%;
    --sidebar-primary-foreground: 0 0% 98%;
    --sidebar-accent: 240 4.8% 95.9%;
    --sidebar-accent-foreground: 240 5.9% 10%;
    --sidebar-border: 220 13% 91%;
    --sidebar-ring: 217.2 91.2% 59.8%;
  }
 
  .dark {
    --sidebar-background: 240 5.9% 10%;
    --sidebar-foreground: 240 4.8% 95.9%;
    --sidebar-primary: 0 0% 98%;
    --sidebar-primary-foreground: 240 5.9% 10%;
    --sidebar-accent: 240 3.7% 15.9%;
    --sidebar-accent-foreground: 240 4.8% 95.9%;
    --sidebar-border: 240 3.7% 15.9%;
    --sidebar-ring: 217.2 91.2% 59.8%;
  }
}

You can customize the colors by overriding these variables in your CSS file. Apply the dark class to switch to a dark theme.

Persistent State Management

The SidebarProvider supports persisting the sidebar state across page reloads and server-side rendering. It uses cookies to store the current state of the sidebar. When the sidebar state changes, a default cookie named sidebar:state is set with the current open/closed state. This cookie is then read on subsequent page loads to restore the sidebar state.

To persist sidebar state in Next.js, set up your SidebarProvider in app/layout.tsx like this:

import { cookies } from "next/headers"
 
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
 
export async function Layout({ children }: { children: React.ReactNode }) {
  const cookieStore = await cookies()
  const defaultOpen = cookieStore.get("sidebar:state")?.value === "true"
 
  return (
    <SidebarProvider defaultOpen={defaultOpen}>
      <AppSidebar />
      <main>
        <SidebarTrigger />
        {children}
      </main>
    </SidebarProvider>
  )
}

You can change the name of the cookie by updating the SIDEBAR_COOKIE_NAME variable in sidebar.tsx.

Advanced Features

Keyboard Shortcuts

The SIDEBAR_KEYBOARD_SHORTCUT variable is used to set the keyboard shortcut used to open and close the sidebar.

The default shortcut is Ctrl+b on Windows/Linux and Cmd+b on macOS. You can change this by updating the SIDEBAR_KEYBOARD_SHORTCUT variable in sidebar.tsx.

const SIDEBAR_KEYBOARD_SHORTCUT = "b"; // Default is cmd+b or ctrl+b
 
<SidebarProvider keyboardShortcut={SIDEBAR_KEYBOARD_SHORTCUT}>
  <Sidebar />
</SidebarProvider>

Sidebar Trigger

Use the SidebarTrigger component to add a trigger button for opening and closing the sidebar. The SidebarTrigger component must be used within a SidebarProvider.

<SidebarProvider>
  <Sidebar />
  <main>
    <SidebarTrigger />
  </main>
</SidebarProvider>

CustomTrigger

To create a custom trigger, you can use the useSidebar hook:

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

Conclusion

The Shadcn Sidebar component is a powerful tool for building navigation components in React applications. Its composable design, customizability, theming support, and persistent state management make it a popular choice among developers. By using the Shadcn Sidebar component, you can create beautiful and functional sidebars that enhance the user experience of your web applications.

If you are looking for a versatile and easy-to-use sidebar component for your React projects, give the Shadcn Sidebar a try. You can find more information about the Shadcn Sidebar component and other Shadcn components on the official website. Happy coding!