Local hash links in Next.js routes to the root page instead of the desired div

We can have links that scroll to some content inside the same page as described in this doc Linking within pages in Builder.io - Builder.io.

But at the moment if we click such a link with hash URL (starts from #) it would update the current page URL to the root page instead of staying on the same page, see demo video

Steps to reproduce

Set up a new project using https://github.com/BuilderIO/nextjs-shopify repository.

  1. Create a Button and set its URL to #id-section (starts from “#”)
  2. (optionally) create a Box and add a custom element attribute “id” with value “id-section”
  3. Click “View current draft”, the page would have a long URL like this https://jolly-wozniak-731104.netlify.app/landing-poc-tests?builder.cachebust=true&builder.preview=page&builder.noCache=true&__builder_editing__=true&builder.overrides.page=33a8fa71eac04355a103b08566ea2477&builder.overrides.33a8fa71eac04355a103b08566ea2477=33a8fa71eac04355a103b08566ea2477&builder.overrides.page:/landing-poc-tests=33a8fa71eac04355a103b08566ea2477
  4. Now click the Button, the page URL in the browser would be updated to the root page https://jolly-wozniak-731104.netlify.app/#id-section.

Expected behavior: the URL should stay the same and only hash #id-section should be added at the end of the URL so the URL should become https://jolly-wozniak-731104.netlify.app/landing-poc-tests?builder.cachebust=true&builder.preview=page&builder.noCache=true&__builder_editing__=true&builder.overrides.page=33a8fa71eac04355a103b08566ea2477&builder.overrides.33a8fa71eac04355a103b08566ea2477=33a8fa71eac04355a103b08566ea2477&builder.overrides.page:/landing-poc-tests=33a8fa71eac04355a103b08566ea2477#id-section

Hi @maxceem , I appreciate the write up here, it was very helpful in fixing this.

The origin of this issue is that next/link doesn’t seem to handle local hash links correctly, I updated the starter code to check if it’s local hash link and render a regular a tag instead, you can see the fix in this commit

1 Like

Wow! Thank you for so quick fix @aziz!

It works perfectly as per quick testing!

Hi, I am having the same issue. We are using this with Angular. I am on Chrome (96.0.4664.55) on Mac OS Big Sur.

After assigning an ID to an element and then linking another element to that ID, the browser loads the root /#id instead of /current-page#id when the linked element is clicked.