Closing Sheet component from within a component inside the SheetContent #1790
-
I have a use case where I wanna close the sheet component when I click on any link. <Sheet>
<SheetTrigger asChild>
<Button variant={"ghost"} size={"icon"} className="lg:hidden">
<Menu />
</Button>
</SheetTrigger>
<SheetContent side={"left"} className="p-0">
<Navbar />
</SheetContent>
</Sheet> {NavbarLinks.map((item) => (
<Link
key={item.id}
className={cn(
"font-semibold transition-all delay-75 text-[17px] dark:text-muted-foreground
dark:hover:text-white text-gray-500 hover:text-gray-900 ",
font.className
)}
href={item.href}
>
{item.label}
</Link>
))} And, I want the Upon clicking on these links the sheet component closes. Can someone suggest me a way of doing that! |
Beta Was this translation helpful? Give feedback.
Replies: 8 comments 11 replies
-
You can do: {NavbarLinks.map((item) => (
<SheetClose asChild>
<Link
key={item.id}
className={cn(
"font-semibold transition-all delay-75 text-[17px] dark:text-muted-foreground
dark:hover:text-white text-gray-500 hover:text-gray-900 ",
font.className
)}
href={item.href}
>
{item.label}
</Link>
</SheetClose>
))} |
Beta Was this translation helpful? Give feedback.
-
Thank you very much @joaom00 ! |
Beta Was this translation helpful? Give feedback.
-
Thank you @joaom00 |
Beta Was this translation helpful? Give feedback.
-
Thank You @joaom00 |
Beta Was this translation helpful? Give feedback.
-
You saved me @joaom00 |
Beta Was this translation helpful? Give feedback.
-
Thank you @joaom00 |
Beta Was this translation helpful? Give feedback.
-
Thanks @joaom00🙌! Went with the second option. But it seems to introduce another issue when you are rendering the component within another section of the website that doesn't need to trigger the sheet close and the setOpen() function. It totally hard reloads the page and throws a NextJS error. Solved this by marking setOpen() as optional within the component:
and conditional setting it on the onClick prop:
|
Beta Was this translation helpful? Give feedback.
-
Thank you so much @joaom00 !! |
Beta Was this translation helpful? Give feedback.
Here an example: https://codesandbox.io/s/upbeat-galileo-6rxfm7?file=/src/App.tsx
because it uses context to close the sheet so it needs to be inside
<Sheet />
which is the context provider