next.js: Link component does not persist scroll position

When using Link for routing and then pressing the browser’s back button, the page will not remember the previous scroll position.

For example, go from page1 to page2 and then click the back button. page1 is rendered at the top of the viewport.

The browser is keeping track of the scroll position because if the page is refreshed it will refresh at the appropriate position. Is this an issue with the History API?

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 21
  • Comments: 23 (15 by maintainers)

Most upvoted comments

@migueloller I don’t think I quite understood the solution @rauchg suggested. The premise is to cache the data on client-side to expedite rendering speed? Did you ever figure out a solution?

Also, @arunoda, you suggested someone could make a PR. Do you have any pointers as to which files or folders I should look at? I would love to make that contribution.

Currently, this is how I’m persisting scroll position with a route listener instance:

function initRouterListeners () {
  const scrollPositions = []
  let hasCompleted = false

  Router.onRouteChangeStart = () => {
    hasCompleted = false
    scrollPositions.push(window.scrollY)
  }
  Router.onRouteChangeComplete = path => {
    hasCompleted = true
  }

  window.onpopstate = popEvent

  function popEvent (e) {
    // sometimes this event fires first
    // and needs to wait for onRouteChangeComplete
    if (hasCompleted) {
      scrollTo()
    } else {
      setTimeout(popEvent, 20)
    }
  }

  function scrollTo () {
    // pop 2 and scroll to that
    scrollPositions.pop()
    const scrollPosition = scrollPositions.pop()

    if (scrollPosition) {
      window.requestAnimationFrame(() => window.scrollTo(0, scrollPosition))
    }
  }
}

This function is called when I bootstrap client. This only works sometimes because data may take too long to load and the browser will scroll to top by default.

I would like a way to persist the scroll position without having to optimizing my render function (I mean I could, but I want to know if there’s a functional way of solving this issue).

Sorry @karanmartian, I saw your message and forgot to reply. Today I found your message again.

I am not working on the project now, but I did this hack to solve it. This code is in my _app.js file, but outside of my App class.

export default class MyApp extends App {
    ....
}

initRouterListeners();

function initRouterListeners() {

    console.log("Init router listeners");

    const routes = [];

    Router.events.on('routeChangeStart', (url) => {
        pushCurrentRouteInfo();
    });

    Router.events.on('routeChangeComplete', (url) => {
        fixScrollPosition();
    });


    // Hack to set scrollTop because of this issue:
    // - https://github.com/zeit/next.js/issues/1309
    // - https://github.com/zeit/next.js/issues/3303

    function pushCurrentRouteInfo() {
        routes.push({pathname: Router.pathname, scrollY: window.scrollY});
    }

    // TODO: We guess we're going back, but there must be a better way
    // https://github.com/zeit/next.js/issues/1309#issuecomment-435057091
    function isBack() {
        return routes.length >= 2 && Router.pathname === routes[routes.length - 2].pathname;
    }

    function fixScrollPosition () {

        let scrollY = 0;

        if (isBack()) {
            routes.pop(); // route where we come from
            const targetRoute = routes.pop(); // route where we return
            scrollY = targetRoute.scrollY; // scrollY we had before
        }

        console.log("Scrolling to", scrollY);
        window.requestAnimationFrame(() => window.scrollTo(0, scrollY));
        console.log("routes now:", routes);
    }
}

@stacygohyunsi You can use scroll prop on link component for your use case like this <Link href="/path" scroll /> Ref: https://github.com/zeit/next.js/blob/master/lib/link.js#L55-L69

Hi, I hope this helps someone.

My requirements:

  • Restore scroll position when pop (when back or forward button clicked)
  • Scroll to top otherwise (For example, on the first load or when navigating with the Link component)

My solution:

// inside _app.tsx

scrollPositionRestorer()

function scrollPositionRestorer() {
  const scrollMemories: { [asPath: string]: number } = {};
  let isPop = false;

  if (process.browser) {
    window.history.scrollRestoration = 'manual';
    window.onpopstate = () => {
      isPop = true;
    };
  }

  Router.events.on('routeChangeStart', () => {
    saveScroll();
  });

  Router.events.on('routeChangeComplete', () => {
    if (isPop) {
      restoreScroll();
      isPop = false;
    } else {
      scrollToTop();
    }
  });

  function saveScroll() {
    scrollMemories[Router.asPath] = window.scrollY;
  }

  function restoreScroll() {
    const prevScrollY = scrollMemories[Router.asPath];
    if (prevScrollY !== undefined) {
      window.requestAnimationFrame(() => window.scrollTo(0, prevScrollY));
    }
  }

  function scrollToTop() {
    window.requestAnimationFrame(() => window.scrollTo(0, 0));
  }
}

Oh, I didn’t know that router return a promise 😃 Thanks!

@coluccini Yes

Router.push('/path').then(() => window.scrollTo(0, 0))