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}>
Sling Academy
</Link>
For more clarity, please see the concrete example below.
Note: In Next.js 12.2 and older, you have to add an <a> tag inside the <Link> component. This action is no longer required in new versions.
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 sling-academy
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>Sling Academy</p>
</header>
<div style={{ height: 1000, background: 'purple' }}></div>
<footer style={{ padding: 30, background: 'pink' }}>
<Link
href='/other-page'
scroll={false}
style={{ color: 'blue', textDecoration: 'underline' }}
>
Go to Other page
</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.
Notice that we made the pages taller than necessary to illustrate the scrolling more clearly. If you have any questions about the code in this article, feel free to leave a comment. Happy coding!