Home > Software engineering >  How to go to the top of the page after clicking the link?
How to go to the top of the page after clicking the link?

Time:08-05

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

CodePudding user response:

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

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

CodePudding user response:

Try to set scrollRestoration in some root component.

 history.scrollRestoration = 'manual';

CodePudding user response:

you can use this hook and put id as it's dependency

useEffect(() => {
   window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth"
        });
}, [id])

if you use it in nextjs, you need to put an if condition in this way

useEffect(() => {

if(typeof window !== 'undefined'){
   window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth"
        });
   }
}, [id])


  • Related