next.js: Router.push('/link') don't scroll top of the page when triggered

Hello,

maybe I am missing something, but when I use this function and redirect to another page scroll doesn’t reset to top but the page loads scrolled to middle, I know why this issue happens, but can I somehow fix it with some flag like JAVASCRIPT Router.pusht({pathname: '/link', scrollreset: true}) or something like this, didn’t find anything similar in documentation

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 10
  • Comments: 34 (9 by maintainers)

Commits related to this issue

Most upvoted comments

I agree there should be a scrollreset option. If you don’t want to do it in componentDidMount you can also do Router.push('/link').then(() => window.scrollTo(0, 0));.

To make it work globally you can use the built-in next.js router event listener: Router.events.on('routeChangeComplete', () => { window.scrollTo(0, 0); });. Just place this in a component shared across all pages e.g. the header.

Hi. Why would we have the Link component default scroll to top true but Router.push not?

I think this issue should be revisited.

Sorry but tagging the contributors: @liweinan0423 @timneutkens @exogen @goldenshun

Router.push('/link').then(() => window.scrollTo(0, 0)); this is the right way to do it, feel free to add it to the readme @gragland ❤️

FWIW, here’s my take on a workaround that was shared in a related issue.

import { useRouter } from 'next/router';
import { useEffect } from 'react';

/**
 * React hook that forces a scroll reset to a particular set of coordinates in the document
 * after `next/router` finishes transitioning to a new page client side. It smoothly scrolls back to
 * the top by default.
 *
 * @see https://github.com/vercel/next.js/issues/3249
 * @see https://github.com/vercel/next.js/issues/15206
 * @see https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions
 * @param {ScrollOptions} [options={}] Hook options.
 * @param {ScrollBehavior} [options.behavior='smooth'] Specifies whether the scrolling should animate smoothly,
 *  or happen instantly in a single jump.
 * @param {number} [options.left=0] Specifies the number of pixels along the X axis to scroll the window.
 * @param {number} [options.top=0] Specifies the number of pixels along the Y axis to scroll the window.
 */
function useRouterScroll({ behavior = 'smooth', left = 0, top = 0 } = {}) {
  const router = useRouter();
  useEffect(() => {
    // Scroll to given coordinates when router finishes navigating
    // This fixes an inconsistent behaviour between `<Link/>` and `next/router`
    // See https://github.com/vercel/next.js/issues/3249
    const handleRouteChangeComplete = () => {
      window.scrollTo({ top, left, behavior });
    };

    router.events.on('routeChangeComplete', handleRouteChangeComplete);

    // If the component is unmounted, unsubscribe from the event
    return () => {
      router.events.off('routeChangeComplete', handleRouteChangeComplete);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [behavior, left, top]);
}

export default useRouterScroll;

Use it somewhere at the top of your component tree (_app.js works).

// _app.js
function MyApp({ Component, pageProps }) {
  // Make sure pages scroll to the top after we navigate to them using `next/router`
  useRouterScroll();

  /* ... */
}

export default MyApp;

This is fixed on next@canary!

whether it should scroll to top or not is decided by the user. I think you can do it in componentDidMount

@Timer @timneutkens Also, got bitten by the difference in behavior of Link and Router.push. FWIW, +1 to adding to the options of Router.push as that would keep it backward compatible.

@timneutkens Is there a reason why the default scroll behavior for the imperative Router.push and <Link> are different? Seems like an obvious bug to me that they behave differently.

@markjackson02 OMHO, the breaking change is that it’s not working that way yet! The wrong behavior’s already made. So I think it would be a good idea to put it the way that it should. But I agree with you, contributors will probably not give attention here.

Here’s a simplified version of @nfantone’s useRouterScroll hook above without any bells and whistles. 😅

import {useRouter} from 'next/router';
import {useEffect} from 'react';

export default function useRouterScroll() {
  const router = useRouter();
  useEffect(() => {
    const handler = () => {
      window.scrollTo(0, 0);
    };
    router.events.on('routeChangeComplete', handler);
    return () => {
      router.events.off('routerChangeComplete', handler);
    };
  });
}

I just want to chime in and say I found this behavior extremely surprising. Been building production sites with Next.js for almost a year now and only just now discovered that Router.push wasn’t returning to the top – I always thought Router.push behaved exactly like <Link> but was just the programmatic way to do it.

And in terms of matching default behavior like <a> vs. <Link>, the non-SPA equivalent of Router.push would seem to be setting window.location which also returns you to the top of the page, no? It would make more sense as the default behavior to me.

It would be nice if there was an option on router.push() to force scroll to top, but I don’t think it should be default as it would be a breaking change for everyone already assuming it does not do this.

@Timer Hi, FYI this is not documented in https://nextjs.org/docs/api-reference/next/router#routerpush - Would be good to add there.

@markjackson02 I don’t see how this would be a breaking change since this is the default way browser would have handle this. I do not agree with the fact that we have two different approaches for the same functionality.

Is NOT fixed with 10.0.8-canary.15, atleast not when using a new basePath in next.config.js

Router.back() doesn’t return promise, but has the same issue, what to do, manually scrolling up?

Woaw… You mean I need to review every single page to add .then()! By the way, I’m using next-routes, so is there a way to add this globally, just to add this code once, like addRequestTransform if you need to add some headers before calling an API.

An old-school workaround from me. Just get the particular component in the view. Here’s how. I use it with the router.push(“/myaccount”) for my peace of mind! I’m using react device detect. For some reason, in mobile browsers, it is not going to the top of the page after clicking router.push. The desktop browser is working fine. So, I wrapped my mobile menu bar Whatever happens, my component will be smoothly scrolled to the top! 😅

import React, { useEffect, useRef } from 'react';

function MyAccount() {
  const containerRef = useRef(null);

  useEffect(() => {
    setTimeout(() => {
      containerRef.current.scrollIntoView({ behavior: 'smooth' });
    }, 250);
  }, []);

  return (
    <div ref={containerRef}>
{/*   It will be your particular component that 
        needs to be scrolled to the top after users click to router.push 
       In my case, it's menubar.
*/}
        <MenuBar /> 
    </div>
  );
}

export default MyAccount;

if you don’t mind using router.push after it being instantiated with useRouter() you can simply do:

    const router = useRouter();
    // ... do stuff
    // page you want to go to, data you want to query, etc.
    router.push(
      // query params, URL, etc.
      null,
      { scroll: false }
    );

{scroll: false} is what prevents scroll to top.

You can use this to route and scroll to the top of the page:

// route using nextjs router and scroll to the top of the page
const routeToTop = (router, ...args) => {
    if(typeof window !== 'undefined') window.scrollTo(0, 0)
    return router.push.apply(router, args)
}

// usage

const router = useRouter()

routeToTop(router, '/my/page')

routeToTop(router, '/articles/[slug]', `/articles/${article.slug}`)

routeToTop(router, {
    pathname: '/search',
    query: {q: searchQuery},
})

Btw, this isn’t as nice of a user experience as the Link behavior, since you scroll to the top of the page immediately instead of when the next page loads.

It would definitely be a breaking change. People have been building apps with the way it is now and expect it to function that way.

I’m not against them both having the same default functionality but I don’t think it’s worth the migration effort.

Anyway, this issue is closed so we should open a new issue with whatever we want to do.

Thanks @gralagland your solution seems not so ugly, but it would be nice to have such option to keep DRY principe. The only fast solution for now is to make live template to write this 😅