Skip to content

Setting up Shadcn UI

When using Shadcn UI within an Astro project, there is a common mistake that prevents Shadcn UI from working properly. With Astro’s islands architecture, React context is not shared between islands. That means that calling Shacdn UI components directly in a .astro file will fail because islands are not able to communicate together. This can be easily solved by moving those components calls to a .jsx/tsx file and importing this one instead.

If you want to see a more interactive example that might help explain or let you test things out better you can:

  1. Follow the getting started guide from the Shadcn UI documentation to set up the library in your project.

  2. Add the Drawer component to your project:

    Terminal window
    npm i npx shadcn@latest add drawer
  3. Create a Drawer Component in your project:

    src/components/MyDrawer.tsx
    import { Button } from "@/components/ui/button";
    import {
    Drawer,
    DrawerClose,
    DrawerContent,
    DrawerDescription,
    DrawerFooter,
    DrawerHeader,
    DrawerTitle,
    DrawerTrigger,
    } from "@/components/ui/drawer";
    export const MyDrawer = () => {
    return (
    <Drawer>
    <DrawerTrigger>Open</DrawerTrigger>
    <DrawerContent>
    <DrawerHeader>
    <DrawerTitle>Are you absolutely sure?</DrawerTitle>
    <DrawerDescription>This action cannot be undone.</DrawerDescription>
    </DrawerHeader>
    <DrawerFooter>
    <Button>Submit</Button>
    <DrawerClose>
    <Button variant="outline">Cancel</Button>
    </DrawerClose>
    </DrawerFooter>
    </DrawerContent>
    </Drawer>
    );
    };
  4. Import the MyDrawer component in the src/pages/index.astro file:

    src/pages/index.astro
    ---
    import { MyDrawer } from "@/components/MyDrawer"
    import '@/styles/globals.css'
    ---
    <html lang="en">
    <head>
    <title>Astro</title>
    </head>
    <body>
    <MyDrawer client:load />
    </body>
    </html>

To learn more about Shadcn UI: