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/