Why Nextjs Link scroll to top not working, when I change route

Viewed 4056

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.

2 Answers

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

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.

Related