8

I am using next/link, but when I change the route, scroll to top not working.

<Link href="/some-page" scroll={false}> Go</Link>

What I should do? I try too much methods and I did not have result.

programm011
  • 141
  • 1
  • 1
  • 6

4 Answers4

3

Your code is disabling the scroll to top by using scroll={false}

via the documentation:

The default behavior of Link is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, like a normal tag. To prevent scrolling to the top / hash scroll={false} can be added to Link:

Remove the scroll={false} to resolve.

Ramakay
  • 2,919
  • 1
  • 5
  • 21
  • 2
    Thank you for answer. I tried without scroll={false}, but did not work – programm011 Mar 08 '22 at 04:40
  • Please provide a MRE so it can be further troubleshooted https://stackoverflow.com/help/minimal-reproducible-example - you can additionally use stackblitz or codesandbox to show what is happening – Ramakay Mar 08 '22 at 15:50
3

You can create this component and import it on the page where you want to scroll to the top.

If you're using a version older than NextJS 13, then just remove the "use client";.

// scrollToTop
"use client";
import { useEffect } from "react";
import React from "react";

export default function scrollToTop() {
  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);
  return null;
}

Import it on the page where you want to scroll to the top:

// examplePage
import React from "react";
import ScrollToTop from "./scrollToTop"; // imported scroll to top

const Page = () => {
  return (
    <>
      <ScrollToTop />
      <div>Text...</div>
    </>
  );
};

export default Page;

Now whenever you enter or refresh the page, it will always scroll to the top.

  • good workaround, however there is no need to add this extra code since we have the same behaviour with Link in Nextjs the scroll props is set to true by default, we can even manually set it. – ShueiYang Jul 23 '23 at 17:42
2

So,I solved the problem with this way:

import { useEffect } from "react";
import { useRouter } from "next/router";
export default function ToTop(){
    const router = useRouter();
    useEffect(()=>{
      const handleRouteChange = () => {
          document.getElementById('top').scrollIntoView();
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    },[]);

    return ('');
}

but I did not like it

programm011
  • 141
  • 1
  • 1
  • 6
0

in my case i had shallow prop on my link which allows you to change the URL without running data fetching methods again

Before:

<Link
    key={i}
    href={``}
    shallow    //<-- remove this         
>
  ...
</Link>

after:

<Link
        key={i}
        href={``}                     
>
      ...
</Link>