next.js: Jump link anchors dont work

Bug report

Describe the bug

When clicking an anchor tag in a different page with a jump to id tag, it raises an error and doesnt go.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

<a className='nav-link' href='https://github.com/zeit/next.js/#documentation' > Docs </a>

Expected behavior

should redirect to github and scroll to documentation tag

Screenshots

Screenshot 2020-03-16 at 15 13 05

System information

  • Browser (if applies): Chrome
  • Nextjs version: 9.1.6

Additional context

I’ve tried this in another project without nextjs and it works fine i also tried in a random place like

https://jsfiddle.net/uqxck4jv/

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 12
  • Comments: 38 (3 by maintainers)

Commits related to this issue

Most upvoted comments

Here is how i adapted the above because it doesn’t work on mobile for me:

  React.useEffect(() => {
    const path = window.location.hash
    if (path && path.includes("#")) {
      setTimeout(() => {
        const id = path.replace("#", "")
        const el = window.document.getElementById(id)
        const r = el.getBoundingClientRect()
        window.top.scroll({
          top: pageYOffset + r.top,
          behavior: "smooth",
        })
      }, 600)
    }

Have this exact same issue.

Why is this not a priority for the Nextjs team? This is breaking a pretty common web pattern for any sites built on top of Nextjs.

Just use Link component instead of a tag =)

My ultra-nonsensical solution for this problem, as I needed it asap:

useEffect(() => {
    const path = window.location.hash
    if (path && path.includes('#')) {
      const id = path.replace('#', '')
      const el = window.document.getElementById(id)
      const r = el.getBoundingClientRect()
      window.scrollTo({
        top: r.top,
        behavior: 'smooth'
      })
    }
  })

Experiencing this issue in NextJS 11 too. I’m linking from "/page-a" to "/page-b#foo". I think my issue is made worse by the fact that the #foo section on Page B is below the fold, so there’s some conflict going on with lazy loading.

A combination of the techniques above is what I ended up going with as a work-around for now:

useEffect(() => {
  const hash = window.location.hash
  if (hash) {
    setTimeout(()=> {
      document
        .querySelector(hash)
        .scrollIntoView({ behavior: "smooth" })
    }, 100)
  }
})

Same issue. Page doesn’t scroll to jump link if come from another page. Jump links only work within the same page

We were still seeing this no scrolling to anchor issue in next 10 (on initial page load. Anchors scroll fine if you’re already navigating from other pages). For some reason the getBoundingClientRect wasn’t correctly calculating the scroll position… We used scrollIntoView. Can add a setTimeout, per another example above if needed.

  useEffect(() => {
    const path = window.location.hash;
    if (path && path.includes('#')) {
      const id = path.replace('#', '');
      if (id) {
        document
          .querySelector('#' + id)
          .scrollIntoView({ behavior: 'smooth' });
      }
    }
  });

Same problem

Came across this and using ref to scroll into view.

e.g. when navigating to /examplepage/#mySection or /examplepage/#myOtherSection

const ExamplePage = () => {
  const router = useRouter();
  const mySection = useRef(null);
  const myOtherSection = useRef(null);

  useEffect(() => {
    const path = router.asPath;
    if (path && path.includes('/#')) {
      const sectionName = path.replace('/#', '');
      switch (sectionName) {
        case 'mySection':
          mySection.current.scrollIntoView({ behavior: 'smooth' });
          break;
        case 'myOtherSection':
          myOtherSection.current.scrollIntoView({ behavior: 'smooth' });
          break;
        default:
          break;
      }
    }
  }, [router.asPath]);

  return (
    <div>
      <section ref={mySection}>
         My section
      </section>
      <section ref={myOtherSection}>
         My section
      </section>
    </div>
  )
}

Maybe it’s useful for somebody: Still far from a sensible fix, but this code saved me from calculating object positions etc. It’s using the native browser function by just reseting the hash.

  useEffect(() => {
    const hash = window.location.hash
    window.location.hash = ''
    window.location.hash = hash
  })

This is a quick uncomplicated fix, thanks!

PS Changed to this, otherwise a ‘#’ is added to every url:

  useEffect(() => {
    const hash = window.location.hash
   if (hash.length>0) {
     window.location.hash = ''
     window.location.hash = hash
   }
  })

Seeing the same issue on Next v12.0.9 - anchors work when you click a link within the same page, but if you refresh or navigate to another page by clicking <Link href={"/secondPage#subsection"} > you end up at the top of page.

make sure that the #subsection element is not behind some async logic or anything that would cause that element not be in the DOM yet i. e. at render time in the full refresh scenario

in regard to my earlier comments and my particular case - the culprit was custom auth logic which delayed DOM rendering on some pages which in turn prevented scroll-to-anchor behaviour on SSR pages. hence it was a very custom source of app bug in my case.

to be clear I never experienced the explicit js error described in the original issue above. I trust that original bug was fixed and provided that assumption is correct, this GH issue should be fixed to prevent more confusion @Timer

I trust other suggested solutions mainly around using setTimeout or employing other 3rd party packages for a simple scroll fix are not optimal. perhaps these suggestions are trying to fix some other issue with scrolling / anchors or their bugs are rooted in the custom app as it was in my case.

finally, previously mentioned events document.addEventListener('DOMContentLoaded', () => {... and window.addEventListener('load', () => {... do work perfectly well in _document.tsx; you may struggle with Script by next/script because of afterInteractive strategy. once again a fix based on either DOM event was not necessary in my case at the end of the day.

This was super helpful… thanks a lot

in regard to my earlier comments and my particular case - the culprit was custom auth logic which delayed DOM rendering on some pages which in turn prevented scroll-to-anchor behaviour on SSR pages. hence it was a very custom source of app bug in my case.

to be clear I never experienced the explicit js error described in the original issue above. I trust that original bug was fixed and provided that assumption is correct, this GH issue should be fixed to prevent more confusion @Timer

I trust other suggested solutions mainly around using setTimeout or employing other 3rd party packages for a simple scroll fix are not optimal. perhaps these suggestions are trying to fix some other issue with scrolling / anchors or their bugs are rooted in the custom app as it was in my case.

finally, previously mentioned events document.addEventListener('DOMContentLoaded', () => {... and window.addEventListener('load', () => {... do work perfectly well in _document.tsx; you may struggle with Script by next/script because of afterInteractive strategy. once again a fix based on either DOM event was not necessary in my case at the end of the day.

Just install https://www.npmjs.com/package/react-scrollchor and worked! Have a nice day of coding guys!

Maybe it’s useful for somebody: Still far from a sensible fix, but this code saved me from calculating object positions etc.

It’s using the native browser function by just reseting the hash.

  useEffect(() => {
    const hash = window.location.hash
    window.location.hash = ''
    window.location.hash = hash
  })

May a suggest:

useEffect(() => {
	setTimeout(()=>{
		router.replace(window.location.href)
	}, 50)
}, [window.location.hash]) // Fires every time hash changes

Any updates here? In the light of NextJs 10 release. Maybe somebody can post a clear workaround here for the time being? I’ve tried several approaches found on SO but couldn’t make it work.