Search code examples
javascriptreactjsnext.jsshadcnui

Controlling Drawer using state In ShadCN and NextJS


I have the following shadcn drawer component implemented in the following manner:

              <Drawer
                open={showCustomizationDrawer}
                onOpenChange={setShowCustomizationDrawer}>
                <DrawerTrigger
                  className="absolute right-[15%] bottom-[5px]"
                  asChild>
                  <Button className="absolute right-[15%] bottom-[5px]">
                    Add
                  </Button>
                </DrawerTrigger>
                <DrawerContent>
                  ...
                </DrawerContent>
              </Drawer>

As you can see the opening of the drawer is controlled by the showCustomizationDrawer state which takes boolean values. All works as expected when i use the drawer trigger, opens and closes as expected. But now outside of this drawer i have a button with the following onClick:

              onClick={() => {
                setShowCustomizationDrawer(true);
              }}

I expect the drawer to open when i click this button, since im changing the state of the showCustomizationDrawer state. There are no errors on the console either.


Solution

  • First of all, the repo in the comments is not a real reproduction. Reproduce the issue is to start a new project that doesn't have anything else but the issue being described.

    I tried to reproduce it simply and it works fine:

    "use client";
    
    import { Button } from "@/components/ui/button";
    import { Drawer, DrawerContent, DrawerTrigger } from "@/components/ui/drawer";
    import { useState } from "react";
    
    export default function Page() {
      const [isOpen, setIsOpen] = useState(false);
    
      console.log("isOpen", isOpen);
    
      return (
        <Drawer open={isOpen} onOpenChange={setIsOpen}>
          <Button variant="secondary" onClick={() => setIsOpen(true)}>Another Button</Button>
    
          <DrawerTrigger>Open Drawer</DrawerTrigger>
          <DrawerContent>Drawer Content</DrawerContent>
        </Drawer>
      );
    }
    

    At the previous snippet both of <DrawerTrigger> and <Button> are working as expected and opening the drawer.

    In your case maybe the button sets the state as expected but the other conditions does not presend:

    dish.availableCustomizations &&
      items.filter((item) => item._id === dish._id).length === 0 && 
        <Drawer
          // ...
    

    Try to console.log all showCustomizationDrawer and the other conditions to figure where is the issue.