profile
viewpoint

Ask questionsLink 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?

zeit/next.js

Answer questions fmaylinch

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);
    }
}
useful!
source:https://uonfu.com/
Github User Rank List