'How can I override the default Next JS routing behaviour to terminate a path and ignore sub-paths while delivering entire URL through useRouter?

I want to access page elements using the URL address bar with Next.js to replicate some of React Routers' functionality.

Example:

I have a Next.js page called demo (in pages folder) that I can access with nextjs.com/demo using basic Next.js page routing.

Demo.js renders like this:

<div class="demo">
  <div id="link1">
    ...
  </div>
  <div id="link2">
    ...
  </div>
</div>

I want to be able to go to straight to my #link anchors via the address bar.

e.g.

nextjs.com/demo/link1 takes me to link1

not

nextjs.com/demo#link1 (which I know works fine)

I know I could extract the /link section and convert it to a #link and use the react router to go to it but problem is Nextjs.com gives me a 404 not found because the router (correctly) thinks it's a page. How can I tell the router that the end of the URL for this routing is demo?

How do i achieve this without react router? Is there some middleware magic will allow me to do this for a specific set of routes?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source