0

I have followed guide https://nextjs.org/docs/basic-features/layouts on Next.js about getting layouts working. But my understanding is that scroll position also should not change when switching between routes?

But in my case every time i scroll and then click on one of the links my scroll position resets to top.

_app.tsx

import type { NextPage } from 'next';
import type { AppProps } from 'next/app';
import type { ReactElement, ReactNode } from 'react';
import { Fragment } from 'react';

export type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
  getLayout?: (page: ReactElement) => ReactNode;
};

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout;
};

const App = ({ Component, pageProps }: AppPropsWithLayout) => {
  const getLayout = Component.getLayout ?? ((page) => page);
  return <Fragment>{getLayout(<Component {...pageProps} />)}</Fragment>;
};

export default App;

LayoutMain.tsx

import Link from 'next/link';
import React, { useEffect } from 'react';

const LayoutMain = ({ children }: { children: React.ReactNode }) => {
  useEffect(() => {
    console.log('Header mounted');
    return () => {
      console.log('Header unmounted');
    };
  }, []);

  return (
    <div>
      <div style={{ marginTop: '100px' }}>
        <Link href="/">Home</Link>
        <Link href="/page1">Page 1</Link>
        <Link href="/page2">Page 2</Link>
      </div>

      {children}
    </div>
  );
};

export default LayoutMain;

index.tsx

import type { ReactElement } from 'react';
import { ManyBox } from '../components/ManyBox';
import LayoutMain from '../layouts/LayoutMain';

import type { NextPageWithLayout } from './_app';

const Page: NextPageWithLayout = () => {
  return <ManyBox name="Home" />;
};

Page.getLayout = function getLayout(page: ReactElement) {
  return <LayoutMain>{page}</LayoutMain>;
};

export default Page;

page1.tsx

import type { ReactElement } from 'react';
import { ManyBox } from '../components/ManyBox';
import LayoutMain from '../layouts/LayoutMain';

import type { NextPageWithLayout } from './_app';

const Page1: NextPageWithLayout = () => {
  return <ManyBox name="page1" />;
};

Page1.getLayout = function getLayout(page: ReactElement) {
  return <LayoutMain>{page}</LayoutMain>;
};

export default Page1;

Link to test: https://test-next-js-13-layouts.vercel.app/

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Marius
  • 1,664
  • 2
  • 16
  • 28
  • 1
    That's the expected, default behaviour for `next/link`. You can disable it by setting `scroll={false}` on `Link`. See https://nextjs.org/docs/api-reference/next/link#disable-scrolling-to-the-top-of-the-page & [Next.js maintain scroll position when page Routing](https://stackoverflow.com/questions/59606737/next-js-maintain-scroll-position-when-page-routing). – juliomalves Nov 09 '22 at 14:43

0 Answers0