[DropdownMenu] won't close when using `Link` in Next.js
Bug report
Dropdown is not closing itself when clicking an item within when using it inside of NextJs _app.js.
Reproducible example
@d3v4nt I had a similar issue with react-location's Link component. It looks like it will close correctly if you pass the ref properly to the component.
This is an issue with Next's Link component not properly passing the ref down to the rendered element.
I don't think this is Radix's business, although a mention in the docs would be appreciated as many people are using Next.
Resources to fix ref passing:
- https://stackoverflow.com/questions/65854159/correct-way-to-use-ref-with-next-js-for-a-link-and-an-a
- https://blog.logrocket.com/dealing-with-links-in-next-js/#:~:text=Here%20is%20how%20a%20wrapped%20version%20of%20Link%20is%20going%20to%20work%3A
With react-location's Link I solved it by creating a component that wraps it:
import React from "react";
import type * as Radix from "@radix-ui/react-primitive";
import { Link as LocationLink } from "react-location";
export const Link = React.forwardRef<
React.ElementRef<typeof LocationLink>,
Radix.ComponentPropsWithoutRef<typeof LocationLink>
>((props, ref) => {
return <LocationLink {...props} _ref={ref} />;
});
Here's an example of passing an <a> element wrapped by forwardRef to the Next's <Link> component:
const AnchorWithRef = forwardRef<HTMLAnchorElement, { name: string }>(
function AnchorWithRef({ name }, forwardedRef) {
return <a ref={forwardedRef}>{name}</a>;
}
);
return (
<DropdownMenu.Item>
<Link href={href} passHref>
<AnchorWithRef name={name} />
</Link>
</DropdownMenu.Item>
);
Sadly, the code above did not work. It still triggered a hard page refresh like a normal <a> tag without prefetching the page like what Next's <Link> does out of the box.
To fix this, you can dispatch an Escape keydown event to close the dropdown menu manually. Here's the dirty fix:
function onClick() {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
}
return (
<DropdownMenu.Item>
<Link href={href}>
<a onClick={onClick}>this is a link</a>
</Link>
</DropdownMenu.Item>
);
Another possible solution however this won't work if the link is #something just /something-else
const router = useRouter();
const [isOpen, setOpen] = useState(false);
useEffect(() => {
const closeMenu = () => setOpen(false);
router.events.on("routeChangeStart", closeMenu);
return () => router.events.off("routeChangeStart", closeMenu);
}, [router.events]);
return (
<DropdownMenu.Root open={isOpen} onOpenChange={setOpen}>
<DropdownMenu.Content>
<DropdownMenu.Item>
<NextLink href={item.href}>
<a>{item.label}</a>
</NextLink>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
);
using <DropdownMenu.Root key={activeUrl}> worked for me (thanks @jonsherrard) to let next know which components to rerender
only caveat is if someone is already ON a page and they click that same link, it won't close.
You could also use it asChild. In this example I'm using shadcn ui which is built with Radix UI so this solution should work.
import Link from "next/link";
import { User } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "~/components/ui/avatar";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu";
export default function Menu() {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Avatar className="h-8 w-8 cursor-pointer">
<AvatarImage src="" />
<AvatarFallback>CN</AvatarFallback>
</Avatar>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link href="/profile">
<User className="mr-2 h-4 w-4" /> Profile
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
This is fantastic, thanks a lot for reminding me of asChild @Garwend 👏🏼 🙏🏼
asChild worked for me. Thanks a lot 🙏🏼
asChild did it for me too! By far the easiest, cleanest and simplest solution here.
asChild did it for me too! By far the easiest, cleanest and simplest solution here.
asChild is the intended way to achieve this.
'use client'
import React from 'react'; import Link from 'next/link'; import { links } from "@/constants/appdata"; import { usePathname} from 'next/navigation'; import { useState, useEffect } from 'react';
const Header = () => {
const pathname = usePathname();
const [isMenu, setIsMenu] = useState(false);
const closeMenu = () => {
setIsMenu(!setIsMenu);
};
useEffect(() => {
if (document) {
document.body.style.overflow = isMenu ? 'hidden' : 'auto';
}
}, [isMenu]);
return (
Text
<div className='md:hidden flex flex-col gap-1 cursor-pointer mr-6' onClick={()=>setIsMenu(!isMenu)}> ${isMenu ? "h-[41vh] shadow-lg flex flex-col items-center gap-5 absolute top-16 w-full md:shadow-none" : "hidden md:block md:items-center md:shadow-none"} gap-5 md:h-16 md:flex md:flex-row md:static bg-white md:w-auto md:py-0 px-6 md:px-0 text-center z-50}>
{links?.map((link) => (
${pathname === link.link ? "text-third-color" : "text-gray-400"}} href={link.link} exact={link.exact} onClick={closeMenu}>
{link.text}
) }; export default Header;
isChild is not working when you have a div inside DropdownMenuItem
isChild it's work thanks 👍