15

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
  • 298
  • 1
  • 3
  • 10

3 Answers3

29
<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

Community
  • 1
  • 1
Manuel Bichler
  • 507
  • 5
  • 10
3

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.

LeeMinHo
  • 298
  • 1
  • 3
  • 10
-12

You may disable the scrolling There are two examples bellow

.scrollDisabled {   
    position: fixed;
    margin-top: 0;// override by JS to use acc to curr $(window).scrollTop()
    width: 100%;
}
JS

var y_offsetWhenScrollDisabled=0;

function disableScrollOnBody(){
    y_offsetWhenScrollDisabled= $(window).scrollTop();
    $('body').addClass('scrollDisabled').css('margin-top', -y_offsetWhenScrollDisabled);
}
function enableScrollOnBody(){
    $('body').removeClass('scrollDisabled').css('margin-top', 0);
    $(window).scrollTop(y_offsetWhenScrollDisabled);
}



Another way 



.stop-scrolling {
  height: 100%;
  overflow: hidden;
}


$('body').addClass('stop-scrolling')
LDS
  • 354
  • 3
  • 9
  • Thank you so much for you answer but on next.js boilerplate usually don't mix up with jQuery library. – LeeMinHo Jan 06 '20 at 05:55
  • 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); } – LDS Jan 08 '20 at 15:30