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> ); }
12345678910
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;
123456789101112131415
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> ); }
12345678910
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 ( ... ); }
12345678910111213141516
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:
Credits: Image by Kanenori from Pixabay