React Hustle

NextJS Prevent Scroll to Top on Route Change

JA

Jasser Mark Arioste

NextJS Prevent Scroll to Top on Route Change

Hello hustlers! In this tutorial, you’ll learn how to prevent the scroll-to-top behavior on route change in NextJS.

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:

  1. Password Protect Static Website in NextJS
  2. How to Chain Multiple Middleware Functions in NextJS
  3. How to Setup Role-Based Authentication in NextJS + NextAuth.js
  4. How to Get the User’s Country in NextJS

Credits: Image by Kanenori from Pixabay

Tags:
Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!

Tags

Donate to ReactHustle