ui: [help wanted]: Unable to control multiple sidebars within one Sidebar provider

Describe the bug

I would like to have 2 or 3 sidebars within my project using the shadcn-ui sidebar component. Firstly, its possible to display them as they should look, for example:

1

What i discovered is that only one Sidebar provider can be used to display the sidebars, i have tried using multiple Sidebar providers for each sidebar but they all return a weird space on the page, but i wont show that right now. What I need help with is this: here is my code with nothing much going on, only displaying the sidebars in the positions I want them.

carbon

I want to be able to toggle the open states of each sidebar individually, but that is not working. for context, if i set the collapsible for all of them to “icon”, they will all collapse into the icon state on the click of a single trigger found within the SidebarProvider

![image](https://github.com/user-att

Affected component/components

Sidebar, SidebarProvider

How to reproduce

Copy and paste this basic component:

import {
	Sidebar,
	SidebarHeader,
	SidebarInset,
	SidebarMenu,
	SidebarMenuButton,
	SidebarMenuItem,
	SidebarProvider,
	SidebarTrigger,
} from "../components/ui/sidebar";
import { Command } from "lucide-react";
import { Separator } from "../components/ui/separator";

const Sandbox = () => {
	return (
		<SidebarProvider>
			{/* sidebar 1 */}
			<Collapsible />

			{/* sidebar 2 */}
			<Channels />

			<SidebarInset>
				<header className="sticky top-0 flex shrink-0 items-center gap-2 border-b bg-background p-4">
					{/* toggle the Collapsible */}
					<button>Co</button>
					<Separator orientation="vertical" className="mr-2 h-4" />
					{/* toggle the Channels */}
					<button>Ch</button>
					<Separator orientation="vertical" className="mr-2 h-4" />
					{/* toggle the Right */}
					<button>R</button>
					<SidebarTrigger className="-ml-1" />
				</header>

				<div className="flex">
					<div className="flex flex-1 flex-col gap-4 p-4">
						{Array.from({ length: 10 }).map((_, index) => (
							<div
								key={index}
								className="aspect-video h-12 w-full bg-purple-400 rounded-lg bg-muted/50"
							/>
						))}
					</div>

					{/* sidebar 3 */}
					<Right />
				</div>
			</SidebarInset>
		</SidebarProvider>
	);
};

export default Sandbox;

const Collapsible = () => {
	return (
		<Sidebar collapsible="icon" className="border-r bg-blue-600 z-50">
			<SidebarTrigger />
			<SidebarHeader>
				<SidebarMenu>
					<SidebarMenuItem>
						<SidebarMenuButton
							size="lg"
							asChild
							className="md:h-8 md:p-0"
						>
							<a href="#">
								<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
									<Command className="size-4" />
								</div>
								<div className="grid flex-1 text-left text-sm leading-tight">
									<span className="truncate font-semibold">
										Acme Inc
									</span>
									<span className="truncate text-xs">
										Collapsible Sidebar
									</span>
								</div>
							</a>
						</SidebarMenuButton>
					</SidebarMenuItem>
				</SidebarMenu>
			</SidebarHeader>
		</Sidebar>
	);
};

const Channels = () => {
	return (
		<Sidebar collapsible="icon" className="border-r bg-red-400">
			<SidebarHeader>
				<SidebarMenu>
					<SidebarMenuItem>
						<SidebarMenuButton
							size="lg"
							asChild
							className="md:h-8 md:p-0"
						>
							<a href="#">
								<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
									<Command className="size-4" />
								</div>
								<div className="grid flex-1 text-left text-sm leading-tight">
									<span className="truncate font-semibold">
										Acme Inc
									</span>
									<span className="truncate text-xs">
										Channels Sidebar
									</span>
								</div>
							</a>
						</SidebarMenuButton>
					</SidebarMenuItem>
				</SidebarMenu>
			</SidebarHeader>
		</Sidebar>
	);
};

const Right = () => {
	return (
		<Sidebar
			collapsible="icon"
			side="right"
			className="border-l bg-green-400"
		>
			<SidebarHeader>
				<SidebarMenu>
					<SidebarMenuItem>
						<SidebarMenuButton
							size="lg"
							asChild
							className="md:h-8 md:p-0"
						>
							<a href="#">
								<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
									<Command className="size-4" />
								</div>
								<div className="grid flex-1 text-left text-sm leading-tight">
									<span className="truncate font-semibold">
										Acme Inc
									</span>
									<span className="truncate text-xs">
										Right Sidebar
									</span>
								</div>
							</a>
						</SidebarMenuButton>
					</SidebarMenuItem>
				</SidebarMenu>
			</SidebarHeader>
		</Sidebar>
	);
};

Codesandbox/StackBlitz link

No response

Logs

No response

System Info

OS: Linux Mint 22
Browser: Microsoft Edge Browser
React Version: 19

Before submitting

  • I’ve made research efforts and searched the documentation
  • I’ve searched for existing issues

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 6
  • Comments: 31 (1 by maintainers)

Most upvoted comments

Hi everyone, thank you for all these comments. I wanted to share this earlier but was busy with some projects. So I was able to have a two sidebar support using a single Sidebar provider but had to make some changes in the sidebar.tsx. Here you can see the entire file and how I used it. edited shadcn’s sidebar -> https://github.com/DevanceJ/echo/blob/main/components/ui/multisidebar.tsx Usage -> https://github.com/DevanceJ/echo/blob/main/app/echo/layout.tsx Left sidebar -> https://github.com/DevanceJ/echo/blob/main/components/sidebar/app-sidebar.tsx Right sidebar -> https://github.com/DevanceJ/echo/blob/main/components/sidebar/queue-sidebar.tsx

Would’ve loved to explain this in much detail but again pretty busy these days. Changes are pretty clear and seem redundant but this works well.

Anyways you can check the whole project on my profile. Let me know if you have any doubts

@Jacksonmills you’re right! The sidebar state is safed via cookies. So just change the SidebarProvider to take a custom name and you can controll them one by one. Change the setOpen so open via the custom name and not the setted cookie name. Hope this helps. @JolomiTee

const SidebarProvider = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<"div"> & {
    defaultOpen?: boolean;
    open?: boolean;
    onOpenChange?: (open: boolean) => void;
    name: string;
  }
>(
  (
    {
      defaultOpen = true,
      open: openProp,
      onOpenChange: setOpenProp,
      className,
      style,
      children,
      name,
      ...props
    },
    ref
  ) => {
    const isMobile = useIsMobile();
    const [openMobile, setOpenMobile] = React.useState(false);

    // This is the internal state of the sidebar.
    // We use openProp and setOpenProp for control from outside the component.
    const [_open, _setOpen] = React.useState(() => {
      const cookieValue = document.cookie
        .split("; ")
        .find((row) => row.startsWith(`${name}:state=`))
        ?.split("=")[1];
      return cookieValue === "true" ? true : defaultOpen;
    });
    const open = openProp ?? _open;
    const setOpen = React.useCallback(
      (value: boolean | ((value: boolean) => boolean)) => {
        const openState = typeof value === "function" ? value(open) : value;
        if (setOpenProp) {
          setOpenProp(openState);
        } else {
          _setOpen(openState);
        }

        // This sets the cookie to keep the sidebar state.
        document.cookie = `${name}:state=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
      },
      [setOpenProp, open, name]
    );

//Rest of the sidebar code..


//Example
 <SidebarProvider name="YOURE SIDEBAR NAME">
        <Sidebar variant="floating" collapsible="icon" side="right">
          <SidebarContent>
          </SidebarContent>
       </Sidebar>
</SidebarProvider>


I tried @ercnshngit 's but like @hitecSmartHome mentioned the styling was a bit wonky. This was due to some changes in the shadcn sidebar since then I believe.

I took the spirit of their changes and did it myself on the latest (I think I might have slightly edited it but it’s by and large the default shadcn sidebar component).

I improved it a little by making the context keyed off of the name as opposed to having lists of all of the state. I also made it typesafe to the caller by making names T[]. This way after you define the sidebarNames, the other options like defaultOpen are now typesafe.

I also included a new keyboardShortcuts prop to allow for each sidebar to have its own letter as in the original component they were all bound to the same one.

Hope this helps some folks and appreciate all of the other’s replies and variants.

https://gist.github.com/nickzelei/b6f016a971740863bb75f39eb6f91a9e

My impl looks like this:

      <SidebarProvider
        defaultOpen={['left']}
        sidebarNames={['left', 'right']}
        keyboardShortcuts={{ left: 'b', right: 'l' }}
      >
        <SidebarLeft name="left" />
        <SidebarInset className="h-screen flex-1 min-w-0 ">
          <header className="flex h-10 shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-10 bg-sidebar">
            <div className="flex flex-row justify-between items-center gap-2 px-2 pt-4">
                <SidebarTrigger name="left" className="hover:bg-gray-200" />
                <SidebarTrigger
                  name="right"
                  className="hover:bg-gray-200"
                  icon={<PanelRightIcon />}
                />
            </div>
          </header>
          {children}
        </SidebarInset>
        <SidebarRight name="right" />
      </SidebarProvider>

@DevanceJ that’s incredible. Wow. Just what I needed! Thank you! 🥳 Used it in OneTask.me — happy to gift you a lifetime.

@atmnksd here is a Stackblitz link containing my implementation.

The key takeaways here are these:

  1. The ui/sidebar.tsx file has been modified in some parts. The important part is the one given by @Jomo178 regarding setting cookie names

@Jacksonmills, you’re right! The sidebar state is safe via cookies. So just change the SidebarProvider to take a custom name and you can control them one by one. Change the setOpen so open via the custom name and not the setted cookie name. Hope this helps. @JolomiTee

const SidebarProvider = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<"div"> & {
    defaultOpen?: boolean;
    open?: boolean;
    onOpenChange?: (open: boolean) => void;
    name: string;
  }
>(
  (
    {
      defaultOpen = true,
: openProp,
      onOpenChange: setOpenProp,
      className,
      style,
      children,
      name,
      ...props
    },
    ref
  ) => {
    const isMobile = useIsMobile();
    const [openMobile, setOpenMobile] = React.useState(false);

    // This is the internal state of the sidebar.
    // We use openProp and setOpenProp for control from outside the component.
    const [_open, _setOpen] = React.useState(() => {
      const cookieValue = document.cookie
      .split("; ")
       .find((row)=> row.startsWith(`${name}:state=`))
        ?.split("=")[1];
      return cookieValue === "true" ? true : defaultOpen;
    });
    const open = openProp ?? _open;
    const setOpen = React.useCallback(
      (value: boolean | ((value: boolean) => boolean)) => {
        const openState = typeof value === "function" ? value(open) : value;
        if (setOpenProp) {
          setOpenProp(openState);
       } else {
          _setOpen(openState);
        }

        // This sets the cookie to keep the sidebar state.
        document.cookie = `${name}:state=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
      },
      [setOpenProp, open, name]
    );

Rest of the sidebar code.


//Example
 <SidebarProvider name="YOURE SIDEBAR NAME">
        <Sidebar variant="floating" collapsible="icon" side="right">
          <SidebarContent>
          </SidebarContent>
       </Sidebar>
</SidebarProvider>
  1. I have seen that to control each sidebar individually, you have to have each one within its own SidebarProvider.
  2. To control the toggle state of the sidebar both on mobile and desktop, you have to make sure the toggleSidebar hook is called within the SidebarProvider which, for the sake of knowing what I’m doing, splits the providers and the sidebars into different components.
  3. And i almost forgot, im using Zustand state management to trigger the toggling of the sidebar using the useEffectHook that triggers the toggleSidebar function, with the zustand state and the open from the useSidebar hook passed as dependencies

So there you have it, feel free to modify the code to your liking, this is what worked for me in my local sandbox testing

Here is the simple snippet using two SidebarProvider, no need to extra component or configuration.

<div className="flex min-h-svh w-full">
  <SidebarProvider defaultOpen={true}>
    <AppPrimarySidebar />  <!-- primary sidebar -->
    <SidebarInset>
      {children}
    </SidebarInset>
  </SidebarProvider>

  <SidebarProvider className="w-fit">
    <AppSecondarySidebar /> <!-- secondary sidebar -->
  </SidebarProvider>
</div>
Image

I had same issue so i edited the sidebar.tsx minimally.

https://gist.github.com/ercnshngit/e1510e966860e04e47d752d16be3cbc1/revisions

I preferred using a single provider instead of multiple providers to prevent layout shifts. The style added inside the provider configures the overall layout.

Usage:

function DashboardLayout() {
  return (
    <SidebarProvider
      sidebarNames={["main-sidebar", "second-sidebar", "right-sidebar"]}
      style={
        {
          "--sidebar-width": "18rem",
        } as React.CSSProperties
      }
    >
      <AppSidebar name="main-sidebar" />
      <SidebarInset>
        <SidebarTrigger name="main-sidebar" />
        <SidebarTrigger name="second-sidebar" />
        <SidebarTrigger name="right-sidebar" />
      </SidebarInset>
      <SidebarRight
        name="right-sidebar"
        style={
          {
            "--sidebar-width": "18rem",
          } as React.CSSProperties
        }
      />
    </SidebarProvider>
  )
}

Hi everyone, thank you for all these comments. I wanted to share this earlier but was busy with some projects. So I was able to have a two sidebar support using a single Sidebar provider but had to make some changes in the sidebar.tsx. Here you can see the entire file and how I used it. edited shadcn’s sidebar -> https://github.com/DevanceJ/echo/blob/main/components/ui/multisidebar.tsx Usage -> https://github.com/DevanceJ/echo/blob/main/app/echo/layout.tsx Left sidebar -> https://github.com/DevanceJ/echo/blob/main/components/sidebar/app-sidebar.tsx Right sidebar -> https://github.com/DevanceJ/echo/blob/main/components/sidebar/queue-sidebar.tsx

Would’ve loved to explain this in much detail but again pretty busy these days. Changes are pretty clear and seem redundant but this works well.

Anyways you can check the whole project on my profile. Let me know if you have any doubts

Very nice @DevanceJ Thank you

PS: You can use this code ❤️

@DevanceJ that’s incredible. Wow. Just what I needed! Thank you! 🥳 Used it in OneTask.me — happy to gift you a lifetime.

This is lovely

You’re welcome @heymartinadams I’m glad this helped. Wishing you all the best with OneTask.me—great name! Would love to try it out

Just stumbled upon this thread, as I had the same issues.

Thanks @JolomiTee, your stackblitz brought me on the right track. I did get an “document is not defined” error though, pointing to the one within the useState. I fixed it as follows, if anyone has the same error:

const [_open, _setOpen] = React.useState(true)
React.useEffect(() => {
      const cookieValue = document.cookie
        .split("; ")
        .find((row) => row.startsWith(`${name}:state=`))
        ?.split("=")[1]
      _setOpen(cookieValue === "true" ? true : defaultOpen)
    }, [defaultOpen, name])

Even though I can control these separate sidebars, I still have the weird spacing issue if I use 2 SidebarProvider together. If someone has a fix please let me know.

@DevanceJ I had the same issue and it worked finally when I removed ‘w-full’ from some elements in the tree, including the <main> element within the SidebarInset. Don’t know why that is the case though.

You’re welcome @NickWoodward

Hey @NickWoodward, the right sidebar closes to the right because there is a direction based prop passed to the sidebar that defines the direction the sidebar closes into which is the side="right" passed to the Sidebar component. I think it default to left.

haha, can’t believe i missed that - have been using it in my demos all day but just didn’t see it in your code. thanks a lot!

Even though I can control these separate sidebars, I still have the weird spacing issue if I use 2 SidebarProvider together. If someone has a fix please let me know.

@Jomo178 @Jacksonmills I was able to adjust mine with the solution @Jomo178 implemented.

So from the screenshot below, I have wrapped each sidebar with the Provider, passed unique names to each, and then put the SidebarTrigger within the Sidebar and with that, each one is isolated and controlled individually

Screenshot from 2024-11-03 22-11-01

image

What I want to test out now is how it works on mobile… because right now, it all disappears… likely into the sheet form, waiting to be triggered and there is no way to trigger it yet with my current UI 😃

Another option is to track each sidebar via an id on the provider and then you can track/toggle specific matching sidebars/toggles

You would need to make the state a bit more complex but it’s definitely doable

@Jomo178 the only way I know of is to have a SidebarProvider wrapped around each individual sidebar instead of the whole App. Doing that, you can set individual widths, collapsible state too and most of all, control them individually. The only downside I have seen with this is that it takes away the mobile responsiveness of the sidebar… Whereby the Sheet component doesn’t come out anymore. This might be due to my many tweakings of the sidebar.tsx file which I had to do to get what I wanted to achieve.