Next.js Link: Disable auto scrolling to top on page changes

Last updated on May 23, 2022 A Goodman Loading... Post a comment

In Next.js, when a user navigates from one page to another page by clicking on a <Link> component, they will be scrolled to the top of the destination page. This is the default behavior and it makes sense in almost common use cases. However, in some specific scenarios, you might want to maintain the scroll position. To do so, simply set the scroll prop of your <Link> component to false:

<Link href="/some-page" scroll={false}>
   <a>KindaCode.com</a>
</Link>

For more clarity, please see the concrete example below.

The Complete Example

App Preview

The small demo we’re going to build contains two pages:

  • /: HomePage
  • /other-page: OtherPage

In the footer area of HomePage, there’s a link that you can use to navigate to OtherPage. When going to OtherPage, you’ll stay at the bottom of it (instead of the top area).

Here’s how it works:

The Code

1. Initialize a brand new Next.js project:

npx create-next-app kindacode-example

Choose another name if you want.

2. Replace all of the default code in your pages/index.js file with the following:

// pages/index.js
import Link from 'next/link'

export default function Home(props) {
  return <>
    <header style={{ padding: 30 }}>
      <h1>Home Page</h1>
      <p>KindaCode.com</p>
    </header>

    <div style={{ height: 1000, background: 'purple' }}></div>
    <footer style={{ padding: 30, background: 'pink' }}>
      <Link href="/other-page" scroll={false}>
        <a style={{ color: 'blue', textDecoration: 'underline' }}>Go to Other page</a>
      </Link>
    </footer>
  </>
}

3. Also in the pages folder, add a new file named other-page.js the add the code below into it:

// pages/other-page.js
const OtherPage = () => {
    return <>
        <header style={{ padding: 30 }}>
            <h1>Other Page</h1>
        </header>

        <div style={{ height: 1000 }}></div>
        <footer style={{padding: 30, background: 'orange'}}>
            <h1>Footer (Other Page)</h1>
        </footer>
    </>
}

export default OtherPage

4. Boot your app up by running:

npm run dev

And go to http://localhost:3000 to test your work.

Conclusion

You’ve learned how to prevent a page in Next.js from scrolling to the top after navigation. If you’d like to explore more new and interesting stuff about Next.js and modern React, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles