'NextJs - Link to scroll to a section in same page
I'm using NextJs. I would like to create a link in my header section. This link should take the user to TestimonialsSection on the same page by scrolling.
<Link href={"#TestimonialsSection"}>
<a className={styles.Designation}>Mentor</a>
</Link>
This is the code I tried, but it didn't work. The URL changes though. Thanks in advance
Solution 1:[1]
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-seciton">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"><a>My first section</a></Link>
<Link href="#second-section"><a>My second section</a></Link>
<div id="first-seciton">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}><a>My second section</a></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.
Solution 2:[2]
If it's just a static string you should remove the braces as ????? says above.
If you're making a reusable component where you need to specify the ID from a parent, use a template string and keep the braces.
<Link href={`#${props.id}`}>
<a className={styles.Designation}>Mentor</a>
</Link>
Solution 3:[3]
Try to use Link tag and in URL add #some-link and then in Link tag href with href='#some-link'
<Link href='#some-link'>
// code section
</Link>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kanuos |
| Solution 2 | jiito |
| Solution 3 | Abdulrahim Klis |
