I have a shadcn popover and its content is several buttons. I want to close a popover once button is clicked. How can I do that?
https://ui.shadcn.com/docs/components/popover
I encountered a similar issue while working with the chadcn Calendar component that use a radix popover. I managed to address this problem by implementing a state. Please note that I've omitted some code for brevity, but I'll provide you with the essential concept. Hope that help!
export function Component() {
const [calendarOpen, setCalendarOpen] = useState(false);
return (
<Popover open={calendarOpen} onOpenChange={setCalendarOpen}>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"w-[240px] pl-3 text-left font-normal",
!field.value && "text-muted-foreground",
)}
>
{field.value ? (
format(field.value, "PPP")
) : (
<span>Pick a date</span>
)}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
onSelect={() => {
setCalendarOpen(false);
}}
/>
</PopoverContent>
</Popover>
);
}
In the Radix UI library, there's a <PopoverClose> component available within the Popover module. To utilize it, you would first import the Popover component from shadcn, followed by importing the PopoverClose component directly from Radix UI. Your code would look something like this:
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { PopoverClose } from "@radix-ui/react-popover";
<Popover>
<PopoverTrigger>Open</PopoverTrigger>
<PopoverContent>
Place content for the popover here.
<PopoverClose asChild>
<button>X</button>
</PopoverClose>
</PopoverContent>
</Popover>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With