✏️ Next.js
[pages] Next.js의 Layout
category
✏️ Next.js
date
thumbnail
slug
next-js-layout
author
status
Public
tags
pages router
summary
type
Post
레이아웃
여러 페이지에서 공통으로 사용하는 부분을 Layout으로 만들어서 사용할 수 있다.
기본 레이아웃
사용하는 레이아웃이 한 가지 경우일 때
components 폴더를 만들고 Layout 파일을 생성한다.
import Navbar from './navbar';
import Footer from './footer';
export default function Layout({ children }) {
return (
<>
<Navbar />
<main>{children}</main>
<Footer />
</>
);
}
pages 폴더에 _app.js 파일을 만들고 components/Layout.js 파일을 가져온다.
import Layout from '../components/Layout';
export default function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
페이지마다 다른 레이아웃을 주고 싶을 때
getLayout 프로퍼티를 사용한다.
import Layout from '../components/Layout'
import SubLayout from '../components/SubLayout'
export default function Page() {
return (
/** Your content */
)
}
Page.getLayout = function getLayout(page) {
return (
<Layout>
<SubLayout>{page}</SubLayout>
</Layout>
)
}
_app.js 에서 조건에 따라 레이아웃을 보여주게 한다.
⇒ getLayout 프로퍼티가 있다면 getLayout에 해당 프로퍼티를 넣고, 없다면 기본 레이아웃 컴포넌트로 감싸서 넣고 보여준다.
export default function MyApp({ Component, pageProps }) {
// Use the layout defined at the page level, if available
const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>);
return getLayout(<Component {...pageProps} />);
}