NextJS Prevent Scroll to Top on Route Change
Jasser Mark Arioste
Hello hustlers! In this tutorial, you’ll learn how to prevent the scroll-to-top behavior on route change in NextJS.
Prevent Scroll to Top using <Link/>
To prevent scroll-to-top behavior using the <Link> component, you’ll have to add scroll={false} to props:
import Link from "next/link";
export default function Component() {
return (
<div>
<Link href="/some-page" scroll={false}>
This is a link
</Link>
</div>
);
}
If you want this behavior all across your app, you can extend the link component like so:
// components/NoScrollLink.tsx
import Link, { LinkProps } from "next/link";
import React, { ReactNode } from "react";
type Props = LinkProps & {
children: ReactNode;
};
const NoScrollLink = ({ children, ...props }: Props) => {
return (
<Link {...props} scroll={false}>
{children}
</Link>
);
};
export default NoScrollLink;
you can use it the same way you use the Link component without passing the scroll={false} prop:
import NoScrollLink from "components/NoScrollLink";
export default function Component() {
return (
<div>
<NoScrollLink href="/some-page">
This is a link
</NoScrollLink>
</div>
);
}
Prevent Scroll to Top using router.push
To prevent scroll-to-top behavior using router.push or router.replace you’ll have to add the scroll:false option on the 3rd parameter:
import { useRouter } from "next/router";
...
export default function Component() {
const router= useRouter();
const handleClick = ()=>{
router.push("/some-page", undefined, {
scroll:false
})
router.replace("/some-page", undefined, {
scroll:false
})
}
return (
...
);
}
That’s it!
Conclusion
We learned how to prevent scroll-to-top in a NextJS app using the Link component and next/router.
If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on Twitter .
Further Reading
Improve your NextJS knowledge by reading my previous tutorials:
- Password Protect Static Website in NextJS
- How to Chain Multiple Middleware Functions in NextJS
- How to Setup Role-Based Authentication in NextJS + NextAuth.js
- How to Get the User’s Country in NextJS
Credits: Image by Kanenori from Pixabay


