Menu, MenuList, MenuItem: following an anchor link on the same page immediately scrolls to the top
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
- 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>
- 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>
- 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
Desktop
- OS: Windows, macOS
- Browser: chrome, edge, brave
- Versions: latest
Works as expected in Safari on macOS
Stack
- @material-tailwind/react 2.1.9
- tailwindcss 3.4.1
- React 18.3.1
- Next.js 14.2.3
- Node.js 20.8.1