Next.js maintain scroll position when page Routing

17,280

Solution 1

<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

Solution 2

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.

Share:
17,280

Related videos on Youtube

LeeMinHo
Author by

LeeMinHo

Updated on September 15, 2022

Comments

  • LeeMinHo
    LeeMinHo over 1 year

    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.

  • LeeMinHo
    LeeMinHo over 4 years
    Thank you so much for you answer but on next.js boilerplate usually don't mix up with jQuery library.
  • LDS
    LDS over 4 years
    hey you can change jquery to next.js by google search of the above functions like $(window).scrollTop() will be componentDidMount() { window.addEventListener('scroll', this.onScroll, false); } componentWillUnmount() { window.removeEventListener('scroll', this.onScroll, false); }
  • Ziker
    Ziker over 3 years
    This does seem to break in Next 10 :(