Why does using SidebarMenuButton inside DropdownMenuTrigger cause an error? #6778
Replies: 2 comments 1 reply
-
Root causeWhen you use
The problem occurs when the child component ( <DropdownMenuTrigger> <!-- Renders a button element -->
<SidebarMenuButton>...</SidebarMenuButton> <!-- Rendered as a child -->
</DropdownMenuTrigger> Instead of: <DropdownMenuTrigger asChild> <!-- Doesn't render its own element -->
<SidebarMenuButton {...propsFromTrigger}>...</SidebarMenuButton> <!-- Expected to handle trigger functionality -->
</DropdownMenuTrigger> Alternative SolutionsIf you need to maintain proper semantic HTML (avoiding nested buttons):
function SidebarMenuButton(
{
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>,
ref: React.ForwardedRef<HTMLButtonElement>
) {
const Comp = asChild ? Slot : "button";
const { isMobile, state } = useSidebar();
const button = (
<Comp
ref={ref} // Forward the ref
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
);
if (!tooltip) {
return button;
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
};
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
);
}
// Forward ref using React.forwardRef after function definition
const ForwardedSidebarMenuButton = React.forwardRef(SidebarMenuButton);
ForwardedSidebarMenuButton.displayName = "SidebarMenuButton";
//Export
export { ForwardedSidebarMenuButton as SidebarMenuButton } ;
|
Beta Was this translation helpful? Give feedback.
-
Big thanks! Had the same issue. |
Beta Was this translation helpful? Give feedback.
-
I installed
sidebar-09
in my project using the commandpnpm dlx shadcn@latest add sidebar-09
, but when running the project, I encounter the error below. Additionally, unlike the example shown in this link, clicking on the user avatar doesn’t open the dropdown menu as expected.Could you help me understand why this is happening?
Beta Was this translation helpful? Give feedback.
All reactions