reactjsnext.js

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

  • 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.