Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

javascript - Save and restore window y position in Next js / React

I'm using nextjs Link with shallow and replace properties to change url from /author to /author?book=234523452 when the query is detected page conditionally hides an InfiniteScroll component and show a component with a single book instead. Single book component has a "X" to go back (also wrapped within a Link) so to show again the InfiniteScrollComponent.

What I'm trying to do is save the current window Y on query (single book) and when the "X" gets clicked move to that stored position via useState.

I'd like to mention that unfortunately scroll={false} doesn't work for my case.

this is my page relevant code:

const [scrollPos, setScrollPos] = useState()

const readUrl = (url, bool) => {
  if (url){
    setScrollPos(window.pageYOffset || document.documentElement.scrollTop)
    router.events.on('routeChangeComplete', () => {
      if (typeof window !== "undefined") {

if (url) means it's routing from /author (so with InfiniteScroll component) to /author?book=234523452 (with single book), else means the "X" got clicked basically and so is routing back to /author

The setTimeout(function() seems to work most of the times but not always, and also adds an ugly moving effect to it

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can set scrollPos for reach retainedComponent and there is detailed guidance here

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share