next.js: `` doesn't work with hashes

This is the same as #2098, except for me it is backwards.

#2098 says

it will only work when that link is pressed from another page.

When this link is pressed on the / page, Next will not scroll into that view

But what I experience is that it doesn’t work from another page, and only works when on the page.

For example if I have <Link href="/#who-we-are" /> and I am on /about, clicking it takes me to /#who-we-are but will not scroll me to the section. Once I am at /#who-we-are I can click the link a second time to make it take me to the section.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 1
  • Comments: 15 (7 by maintainers)

Commits related to this issue

Most upvoted comments

window.addEventListener('hashchange', console.log) doesn’t work while using Next.js Router, all the more reason for Next.js to trigger onRouteChangeComplete for hash changes.

If I click on a <Link> that has a hash, there’s no hashchange event fired. I can only trigger it by doing location.hash = 'someValue', which means I would have to step outside Next.js Router and implement something else.

It would be great for hashes to be first-class citizens in Next.js Router!

I was able to fix it with a simple workaround. I’ve added the following to my code which seems to work, making it scroll to the section whenever the route has a hash:

    Router.onRouteChangeComplete = () => {
      setTimeout(() => {
        if (location.hash) location = location
      }, 0)
    };

I hope this doesn’t have any implications. So far everything seems to work well, forward/back browser buttons seems to work as expected.

Before reading all of this issue I’d like to point out the issue template is pretty clear right 🤔 Please use it when creating issues. It saves us a lot of time: https://github.com/zeit/next.js/issues/new/choose