NextJS PageRouter에서 페이지마다 다르게 레이아웃을 가져가는 방법을 알아보자.
getLayout
이라는 함수를 사용하면 된다.
_app.tsx
import '@/styles/globals.css';
import type { AppProps } from 'next/app';
import { NextPageWithLayout } from '@/types/common';
type AppPropsWithLayout = AppProps & {
Component: NextPageWithLayout;
};
export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
// Use the layout defined at the page level, if available
const getLayout = Component.getLayout ?? (page => page);
return getLayout(<Component {...pageProps} />);
}
common.d.ts
// NextJS 중첩 레이아웃을 위한 타입
type NextPageWithLayout<P = NonNullable<unknown>, IP = P> = NextPage<P, IP> & {
getLayout?: (page: ReactElement) => ReactNode;
};
다르게 레이아웃을 적용하고 싶은 페이지에서 아래와 같이 사용하자
index.tsx
import React, { ReactElement } from 'react';
import Layout from '@/components/layout/order/Layout';
import { NextPageWithLayout } from '@/types/common';
const OrderIndexPage: NextPageWithLayout = () => {
return <div>hello world</div>;
};
OrderIndexPage.getLayout = function getLayout(page: ReactElement) {
return <Layout>{page}</Layout>;
};
export default OrderIndexPage;
OrderLayout.tsx
import React, { ReactElement } from 'react';
/**
* 일반인 KIOSK 레이아웃
* @param props
* @constructor
*/
const Layout = (props: { children: ReactElement }) => {
return (
<div className="mx-auto max-w-screen-md h-screen p-40 sm:p-2 md:p-2">
<div className="h-full border-solid border-2 border-b-gray-950">{props.children}</div>
</div>
);
};
export default Layout;