NextJS
[Next.js] 페이지마다 다른 Layout
jinist
2022. 8. 3. 12:46
next.js layout 구현
react에서 페이지마다 다른 layout을 구현해야 했을 때
각각 페이지마다 pageContainer를 넣고 props를 통해 header에 나타나는 요소들을을 제어했었다.
Next에서도 그렇게 작업을 해야 하나 했었는데 알아본 결과 조금은 다른 방식으로 Layout을 제어할 수 있었다.
공식문서에 활용 예시가 굉장히 상세하게 설명되어있다!
_app.tsx
import Layout from '~/components/common/Layout';
export type NextPageWithLayout = NextPage & { getLayout?: (page: ReactElement) => ReactNode };
type AppPropsWidthLayout = AppProps & { Component: NextPageWithLayout };
function MyApp({ Component, pageProps }: AppPropsWidthLayout) {
const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>);
return getLayout(<Component {...pageProps} />);
}
전체 페이지를 감쌀 Layout 컴포넌트를 만들고 component를 감싸주는 코드를 작성해주었다.
CourseCreate.getLayout = function getLayout(page: ReactElement) {
return <Layout full>{page}</Layout>;
};
Layout 변경이 필요한 페이지에는 props 를 통해 변경 가능하도록 지정해주어
페이지마다 다른 레이아웃을 구현할 수 있다.