NextJs – Link to scroll to a section in same page

In vanilla HTML you’d do something like this

<a href="#first-section">My first section</a>
<a href="#second-section">My second section</a>

<div id="first-section">SECTION 1</div>
<main id="second-section">SECTION 2</main>

In NextJS you’d so something similar. Instead of using the anchor tag for linking, you’d use the Link components.

<Link href="#first-section">My first section</Link>
<Link href="#second-section">My second section</Link>

<div id="first-section">SECTION 1</div>
<main id="second-section">SECTION 2</main>

This would work just fine.
However, if you want your starting URL to be www.my-site.com/#second-section, you would need to set the Link component’s scroll prop to false.
Ex:

...
<Link href="#second-section" scroll={false}>My second section</Link>
...

Make sure your sections/divs ie the target elements have the ID attribute set to them properly without the # and the corresponding
anchor links have the # prefixed to ID name

Here’s the official NextJS documentation https://nextjs.org/docs/api-reference/next/link

Hope this resolves your issue.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)