Seperate the drawer in custom component. also use shadcn sidebar to make it.
index.tsx:
'use client'
import { useState } from 'react';
import { Menu, X } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import LanguageSelector from './LanguageSelector';
return (
Language
Select Language
English
العربية
)
}
export default LanguageSelector
Docs:
Structure
A Sidebar component is composed of the following parts:
code
SidebarProvider - Handles collapsible state.
Sidebar - The sidebar container.
SidebarHeader and SidebarFooter - Sticky at the top and bottom of the sidebar.
SidebarContent - Scrollable content.
SidebarGroup - Section within the SidebarContent.
SidebarTrigger - Trigger for the Sidebar.
Sidebar Structure
Usage
app/layout.tsx
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
export default function Layout({ children }: { children: React.ReactNode }) {
return (
{children}
)
}
components/app-sidebar.tsx
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarHeader,
} from "@/components/ui/sidebar"
export function AppSidebar() {
return (
)
}
Your First Sidebar
Let's start with the most basic sidebar. A collapsible sidebar with a menu.
Add a SidebarProvider and SidebarTrigger at the root of your application.
app/layout.tsx
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
export default function Layout({ children }: { children: React.ReactNode }) {
return (
{children}
)
}
Create a new sidebar component at components/app-sidebar.tsx.
components/app-sidebar.tsx
import { Sidebar, SidebarContent } from "@/components/ui/sidebar"
export function AppSidebar() {
return (
)
}
Now, let's add a SidebarMenu to the sidebar.
We'll use the SidebarMenu component in a SidebarGroup.
components/app-sidebar.tsx
import { Calendar, Home, Inbox, Search, Settings } from "lucide-react"
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.
If you need to change the code in sidebar.tsx, you are encouraged to do so. The code is yours. Use sidebar.tsx as a starting point and build your own.
In the next sections, we'll go over each component and how to use them.
SidebarProvider
The SidebarProvider component is used to provide the sidebar context to the Sidebar component. You should always wrap your application in a SidebarProvider component.
Props
Name Type Description
defaultOpen boolean Default open state of the sidebar.
open boolean Open state of the sidebar (controlled).
onOpenChange (open: boolean) => void Sets open state of the sidebar (controlled).
Width
If you have a single sidebar in your application, you can use the SIDEBAR_WIDTH and SIDEBAR_WIDTH_MOBILE variables in sidebar.tsx to set the width of the sidebar.
components/ui/sidebar.tsx
This will handle the width of the sidebar but also the layout spacing.
Keyboard Shortcut
The SIDEBAR_KEYBOARD_SHORTCUT variable is used to set the keyboard shortcut used to open and close the sidebar.
To trigger the sidebar, you use the cmd+b keyboard shortcut on Mac and ctrl+b on Windows.
You can change the keyboard shortcut by updating the SIDEBAR_KEYBOARD_SHORTCUT variable.
components/ui/sidebar.tsx
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
Persisted State
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:
app/layout.tsx
import { cookies } from "next/headers"
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
You can change the name of the cookie by updating the SIDEBAR_COOKIE_NAME variable in sidebar.tsx.
components/ui/sidebar.tsx
const SIDEBAR_COOKIE_NAME = "sidebar:state"
Sidebar
The main Sidebar component used to render a collapsible sidebar.
import { Sidebar } from "@/components/ui/sidebar"
export function AppSidebar() {
return
}
Props
Property Type Description
side left or right The side of the sidebar.
variant sidebar, floating, or inset The variant of the sidebar.
collapsible offcanvas, icon, or none Collapsible state of the sidebar.
side
Use the side prop to change the side of the sidebar.
Available options are left and right.
import { Sidebar } from "@/components/ui/sidebar"
export function AppSidebar() {
return
}
variant
Use the variant prop to change the variant of the sidebar.
Available options are sidebar, floating and inset.
import { Sidebar } from "@/components/ui/sidebar"
export function AppSidebar() {
return
}
Note: If you use the inset variant, remember to wrap your main content in a SidebarInset component.
collapsible
Use the collapsible prop to make the sidebar collapsible.
Available options are offcanvas, icon and none.
import { Sidebar } from "@/components/ui/sidebar"
export function AppSidebar() {
return
}
Prop Description
offcanvas A collapsible sidebar that slides in from the left or right.
icon A sidebar that collapses to icons.
none A non-collapsible sidebar.
useSidebar
The useSidebar hook is used to control the sidebar.
import { useSidebar } from "@/components/ui/sidebar"
Property Type Description
state expanded or collapsed The current state of the sidebar.
open boolean Whether the sidebar is open.
setOpen (open: boolean) => void Sets the open state of the sidebar.
openMobile boolean Whether the sidebar is open on mobile.
setOpenMobile (open: boolean) => void Sets the open state of the sidebar on mobile.
isMobile boolean Whether the sidebar is on mobile.
toggleSidebar () => void Toggles the sidebar. Desktop and mobile.
SidebarHeader
Use the SidebarHeader component to add a sticky header to the sidebar.
The following example adds a to the SidebarHeader.
A sidebar header with a dropdown menu.
components/app-sidebar.tsx
SidebarFooter
Use the SidebarFooter component to add a sticky footer to the sidebar.
The following example adds a to the SidebarFooter.
A sidebar footer with a dropdown menu.
components/app-sidebar.tsx
export function AppSidebar() {
return (
Username
Account
Billing
Sign out
)
}
SidebarContent
The SidebarContent component is used to wrap the content of the sidebar. This is where you add your SidebarGroup components. It is scrollable.
import { Sidebar, SidebarContent } from "@/components/ui/sidebar"
export function AppSidebar() {
return (
)
}
SidebarGroup
Use the SidebarGroup component to create a section within the sidebar.
A SidebarGroup has a SidebarGroupLabel, a SidebarGroupContent and an optional SidebarGroupAction.
A sidebar group.
import { Sidebar, SidebarContent, SidebarGroup } from "@/components/ui/sidebar"
A sidebar group with an action button.
SidebarMenu
The SidebarMenu component is used for building a menu within a SidebarGroup.
A SidebarMenu component is composed of SidebarMenuItem, SidebarMenuButton, and components.
Sidebar Menu
Here's an example of a SidebarMenu component rendering a list of projects.
A sidebar menu with a list of projects.
SidebarMenuButton
The SidebarMenuButton component is used to render a menu button within a SidebarMenuItem.
Link or Anchor
By default, the SidebarMenuButton renders a button but you can use the asChild prop to render a different component such as a Link or an a tag.
Icon and Label
You can render an icon and a truncated label inside the button. Remember to wrap the label in a .
isActive
Use the isActive prop to mark a menu item as active.
SidebarMenuAction
The SidebarMenuAction component is used to render a menu action within a SidebarMenuItem.
This button works independently of the SidebarMenuButton i.e you can have the as a clickable link and the as a button.
DropdownMenu
Here's an example of a SidebarMenuAction component rendering a DropdownMenu.
A sidebar menu action with a dropdown menu.
SidebarMenuSub
The SidebarMenuSub component is used to render a submenu within a SidebarMenu.
Use and to render a submenu item.
A sidebar menu with a submenu.
Collapsible SidebarMenu
To make a SidebarMenu component collapsible, wrap it and the SidebarMenuSub components in a Collapsible.
A collapsible sidebar menu.
SidebarMenuBadge
The SidebarMenuBadge component is used to render a badge within a SidebarMenuItem.
A sidebar menu with a badge.
SidebarMenuSkeleton
The SidebarMenuSkeleton component is used to render a skeleton for a SidebarMenu. You can use this to show a loading state when using React Server Components, SWR or react-query.
We intentionally use different variables for the sidebar and the rest of the application to make it easy to have a sidebar that is styled differently from the rest of the application. Think a sidebar with a darker shade from the main application.
Styling
Here are some tips for styling the sidebar based on different states.
code
Styling an element based on the sidebar collapsible state. The following will hide the SidebarGroup when the sidebar is in icon mode.
code
Styling a menu action based on the menu button active state. The following will force the menu action to be visible when the menu button is active.
To refactor your current Navbar component by separating the drawer into a custom component and integrating the shadcn Sidebar, follow these steps:
Create a Custom Sidebar Component (AppSidebar.tsx)
Update the Application Layout (layout.tsx)
Refactor the Navbar to Use the Sidebar
Adjust Styling and Functionality as Needed
Below is a comprehensive guide with code examples to help you achieve this integration smoothly.
1. Create a Custom Sidebar Component (AppSidebar.tsx)
First, create a new file named AppSidebar.tsx within your components directory. This component will utilize the shadcn Sidebar components to render your navigation items and the language selector.
Navigation Items: The navItems array contains your navigation links along with their corresponding icons. Ensure you replace placeholder icons with the appropriate ones from lucide-react.
Sidebar Structure: The Sidebar component is set to be collapsible as an off-canvas drawer. Inside, it contains SidebarContent which holds SidebarGroup components for organizing your navigation and settings.
Language Selector: The LanguageSelector is included within the sidebar under the "Settings" group. You can adjust its placement as needed.
2. Update the Application Layout (layout.tsx)
Next, incorporate the SidebarProvider and the newly created AppSidebar into your application’s layout. This ensures that the sidebar is available throughout your application.
app/layout.tsx
tsx
'use client';
import { SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar';
import AppSidebar from '@/components/AppSidebar';
import Navbar from '@/components/Navbar';
import '@/styles/globals.css'; // Ensure you have global styles if needed
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<SidebarProvider>
<AppSidebar />
<div className="flex flex-col min-h-screen">
<Navbar />
<main className="flex-1">
{/* SidebarTrigger can be placed anywhere, commonly in the Navbar */}
<SidebarTrigger className="lg:hidden" /> {/* Visible on mobile */}
{children}
</main>
</div>
</SidebarProvider>
);
}
Explanation:
SidebarProvider: Wraps the application to provide sidebar context.
AppSidebar: The custom sidebar component you created is included here.
Navbar: Your existing Navbar component is included within the layout.
SidebarTrigger: Added within the main content to allow triggering the sidebar. You can place it inside the Navbar for better UX.
3. Refactor the Navbar to Use the Sidebar
Now, update your Navbar component to utilize the SidebarTrigger provided by shadcn instead of managing the drawer state manually.
SidebarTrigger: Replaces the manual state management for opening the mobile drawer. By using SidebarTrigger, clicking the button will toggle the sidebar's visibility.
Icon Update: The trigger currently uses the X icon. You might want to toggle between Menu and X based on the sidebar state. To achieve this, you would need to enhance the SidebarTrigger with state awareness or customize the trigger further. However, shadcn's SidebarTrigger handles opening and closing, so you might need to align the icon accordingly or keep it as a single icon.
4. Adjust Styling and Functionality as Needed
Ensure that your application’s styling aligns with the new sidebar integration. Since shadcn's Sidebar uses specific class names and structure, you might need to adjust Tailwind CSS configurations or custom styles to maintain consistency.
Example: Adjusting Sidebar Width and Theming
You can customize the sidebar's width and theming using CSS variables as mentioned in the shadcn documentation.
CSS Variables: Customize the sidebar's appearance by adjusting the CSS variables. This allows for easy theming and adaptability between light and dark modes.
Responsive Design: Ensure the sidebar behaves correctly on different screen sizes by verifying the --sidebar-width and --sidebar-width-mobile variables.
Additional Enhancements
1. Dynamic Icon Toggle in Navbar
If you want the Navbar's mobile trigger to toggle between Menu and X icons based on the sidebar state, you can enhance the SidebarTrigger to access the sidebar state.
However, shadcn's SidebarTrigger does not expose the sidebar's open state directly. To achieve this, you might need to create a custom trigger that uses the useSidebar hook.
// ... other imports
import CustomSidebarTrigger from './CustomSidebarTrigger';
// Replace SidebarTrigger with CustomSidebarTrigger
<div className="lg:hidden">
<CustomSidebarTrigger
className="inline-flex items-center justify-center p-2 rounded-md text-gray-700 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-red-500"
/>
</div>
Explanation:
useSidebar Hook: Accesses the sidebar's open state and toggle function to switch icons accordingly.
CustomSidebarTrigger: A custom button that toggles the sidebar and displays either the Menu or X icon based on the sidebar's state.
2. Persist Sidebar State (Optional)
If you want the sidebar state to persist across page reloads, shadcn's SidebarProvider supports this out of the box using cookies.
Update layout.tsx for Persisted State
app/layout.tsx
tsx
'use client';
import { cookies } from 'next/headers';
import { SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar';
import AppSidebar from '@/components/AppSidebar';
import Navbar from '@/components/Navbar';
import '@/styles/globals.css';
export default function Layout({ children }: { children: React.ReactNode }) {
const cookieStore = cookies();
const defaultOpen = cookieStore.get('sidebar:state')?.value === 'true';
return (
<SidebarProvider defaultOpen={defaultOpen}>
<AppSidebar />
<div className="flex flex-col min-h-screen">
<Navbar />
<main className="flex-1">
<SidebarTrigger className="lg:hidden" />
{children}
</main>
</div>
</SidebarProvider>
);
}
Explanation:
Persisted State: The sidebar's open or closed state is stored in a cookie named sidebar:state. On initial load, the sidebar reads this cookie to set its default state.
Custom Cookie Name: If you wish to change the cookie name, adjust the SIDEBAR_COOKIE_NAME variable within the Sidebar component definitions.
Conclusion
By following the steps above, you've successfully:
Separated the Drawer: Moved the mobile drawer functionality into a dedicated AppSidebar component using shadcn's Sidebar.
Integrated shadcn Sidebar: Utilized shadcn’s composable Sidebar components to build a scalable and customizable sidebar for your application.
Refactored Navbar: Updated the Navbar to use a custom sidebar trigger, enhancing the user experience and maintaining a clean codebase.
Enhanced Functionality: Added optional features like dynamic icon toggling and persisted sidebar state for a more robust implementation.
Feel free to further customize the AppSidebar and Navbar components to better fit your application's design and functionality requirements.