Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 755
nizomiddinzaripov Avatar asked Jan 29 '26 15:01

nizomiddinzaripov


2 Answers

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.

like image 123
Elias Norta Avatar answered Feb 03 '26 01:02

Elias Norta


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.

like image 27
Ramakay Avatar answered Feb 02 '26 23:02

Ramakay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!