creativetimofficial / material-tailwind

@material-tailwind is an easy-to-use components library for Tailwind CSS and Material Design.
https://material-tailwind.com/
MIT License
3.51k stars 306 forks source link

Menu, MenuList, MenuItem: following an anchor link on the same page immediately scrolls to the top #691

Open yuuhn opened 1 month ago

yuuhn commented 1 month ago

Describe the bug

In my Next.js application, in Chrome (macOS, W11), Edge (W11), Brave (macOS) I encountered an issue with adding anchor links to MenuItem: after clicking the button, the page scrolls to the specified anchor but then, immediately jumps to the top. I did NOT observe such behavior in Safari.

The issue persists with an <a> tag around the item

 <MenuList>
    <a href="#test">
      <MenuItem>hello</MenuItem>
    </a>
 </MenuList>

or Next.js router.push() on the item.

<MenuList>
  <MenuItem
    onClick={() => {
      router.push("#test");
    }}
  >
    hello
  </MenuItem>
</MenuList>

I also discovered a workaround: setting a 1-second timeout prevents the issue:

<MenuList>
  <MenuItem
    onClick={() => {
      setTimeout(() => router.push("#test"), 1000);
    }}
  >
    hello
  </MenuItem>
</MenuList>

This made me think there is an event that fires on the MenuList after the page scrolls to the required position.

Linking to other website pages seems unaffected.

To Reproduce

  1. Create an anchor somewhere on the page.
    <div className="h-screen"></div>
    <div id="test" className="text-red-600">
    Test
    </div>
    <div className="h-screen"></div>
  2. Create a Menu with a link to the anchor.
    <Menu open={openNav} handler={setOpenNav}>
    <MenuHandler>
    <IconButton>hello</IconButton>
    </MenuHandler>
    <MenuList>
    <a href="#test">
      <MenuItem>hello</MenuItem>
    </a>
    </MenuList>
    </Menu>
  3. Click on the link in the menu.

I've created a clean project with just this one menu to showcase the issue. To launch it, run npm I && run dev and proceed to http://localhost:3000

Expected behavior

I expect the page to scroll to the anchor without jumping back to the top in every supported browser, not just Safari.

Priority

--

Screenshots/Video

material-tailwind-menu-issue

Desktop

Stack