primitives icon indicating copy to clipboard operation
primitives copied to clipboard

[DropdownMenu] won't close when using `Link` in Next.js

Open anstapol opened this issue 4 years ago • 12 comments

Bug report

Dropdown is not closing itself when clicking an item within when using it inside of NextJs _app.js.

Reproducible example

CodeSandbox Template

anstapol avatar Jan 21 '22 06:01 anstapol

@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} />;
});

hugooliveirad avatar Feb 07 '22 18:02 hugooliveirad

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

rayjasson98 avatar Apr 26 '22 20:04 rayjasson98

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

DonHuskini avatar Jun 17 '22 03:06 DonHuskini

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.

leogilmour avatar Apr 14 '23 18:04 leogilmour

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

Garwend avatar Apr 26 '23 18:04 Garwend

This is fantastic, thanks a lot for reminding me of asChild @Garwend 👏🏼 🙏🏼

CanRau avatar May 08 '23 17:05 CanRau

asChild worked for me. Thanks a lot 🙏🏼

Nemidas7734 avatar Feb 07 '24 05:02 Nemidas7734

asChild did it for me too! By far the easiest, cleanest and simplest solution here.

thomasflensted avatar Feb 22 '24 07:02 thomasflensted

asChild did it for me too! By far the easiest, cleanest and simplest solution here.

asChild is the intended way to achieve this.

benoitgrelard avatar Feb 22 '24 14:02 benoitgrelard

'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)}>
<div className={ ${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) => (
<Link className={${pathname === link.link ? "text-third-color" : "text-gray-400"}} href={link.link} exact={link.exact} onClick={closeMenu}> {link.text}
))}

) }; export default Header;

evgeniy9286 avatar Apr 08 '24 07:04 evgeniy9286

isChild is not working when you have a div inside DropdownMenuItem

syed-afzal60 avatar Jul 23 '24 13:07 syed-afzal60

isChild it's work thanks 👍

staciax avatar Sep 08 '24 14:09 staciax