How to go to the top of the page after clicking the link?

Issue

The problem is, it goes to the middle of the page whenever I navigate to a link in NextJS:

<Link href={`/products/${id}`} key={id}>
   <a>
      {/* other components */}
   </a>
</Link>

So i think the problem is that the link is on the middle of the page so when i click on the link it stays on the same position as where u clicked the link and not go at the top of the page. I know it doesn’t make sense.

I tried adding things like scroll={true}, or scroll={false} to the <Link>. Tried adding height: 100% to html and body in CSS. I tried adding scroll-behavior: smooth; and other stuff. The problem still stays.

Heres the video:
https://drive.google.com/file/d/1CCgFCJb1fl9RRYmW5yp41US-0yuSqpfj/view?usp=sharing

Temporary Solution:
its to not use Link and just use the usual <a> tag. Because <Link> don’t make the page reload whilst <a> tag reloads the page when navigating to another page. so if the page reloads when you click the link then it always starts at the top.

Note: i tried all the solutions below.

Solution

In your page component, inside useEffect hook, put window.scrollTo(0,0)

useEffect(()=>{
  window.scrollTo(0,0);
},[])

Answered By – Abhay Srivastav

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published