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?
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>
);
}