Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js maintain scroll position when page Routing

I am currently making a web site on Next.js boilerplate.

My routing code is this. (below)

import Link from 'next/link'


<Link href={{ pathname: '/some-url', query: { param: something } }}>
  <div>
    <button type="button" onClick={handleClickMore}><span>+ More</span></button>
  </div>
</Link>

when I click this <Button> I do not want scroll position to be moved. But as you know, it moves to the top when the new page is being routed. Does anyone have any idea about maintaining scroll position when the new paged is being loaded.

like image 792
LeeMinHo Avatar asked Jan 06 '20 04:01

LeeMinHo


2 Answers

<Link scroll={false} href="/"><a>Home</a></Link>

scroll={false} will disable the scroll to top on page changes for that specific link.

Reference: https://github.com/zeit/next.js/issues/3950

like image 129
Manuel Bichler Avatar answered Oct 03 '22 09:10

Manuel Bichler


Thank you for the Answer LDS I think I found the answer

when using Router.push() page scroll position doesn't move.

solution code is this.


import Link from 'next/link'

const handleClickMore = () => {
  Router.push({
    pathname: '/story/category/movie/movielist',
    query: { category: props.category, page: (parseInt(props.page) + 1) }
  })
}


<Link href={{ pathname: '/some-url', query: { param: something } }}>
  <div>
    <button type="button" onClick={handleClickMore}><span>+ More</span></button>
  </div>
</Link>

FYI I've skipped the component declaration code.

like image 36
LeeMinHo Avatar answered Oct 03 '22 10:10

LeeMinHo