Frontend/Next.js

[Next.js 14] Layouts

khakhalog 2024. 10. 16. 21:46

Next.js app 라우터 버전에서 layout 파일은 다음과 같은 역할을 한다.

  • 여러 route 간에 공유되는 UI
  • 페이지 이동시 state를 유지하고 interactive 요소를 유지하며 리렌더링이 일어나지 않는다.
  • 레이아웃은 중첩해서 존재할 수 있다.

레이아웃은 기본적으로 layout.js 파일에서 React 컴포넌트를 정의하게 된다.
해당 컴포넌트는 렌더링 중에 자식 레이아웃(존재하는 경우)이나 페이지로 채워질 children prop을 허용해주어야 한다.

📦 app
├── 📄 layout.tsx
│   └── 📂 dashboard   
│       ├── 📄 layout.tsx
│       ├── 📄 page.tsx
│       └── 📂 settings
└────────────└──📄 page.tsx

예를 들어 위와 같은 구조로 /dashboard 페이지와 /dashboard/settings 페이지 간에 레이아웃이 공유되도록 하려면 props로 children을 정의해줘야 한다.

// app/dashboard/layout.tsx

export default function DashboardLayout({
  children, // will be a page or nested layout
}: {
  children: React.ReactNode
}) {
  return (
    <section>
      <nav></nav>
      {children}
    </section>
  )
}

Root Layout (필수)

app 폴더의 최상위에 필수로 존재하는 Root Layout은 모든 라우트에 적용되는 레이아웃이다.
이 루트 레이아웃에는 html, body 태그를 포함한다.

// app/layout.tsx

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="ko">
      <body>
        {/* Layout UI */}
        <main>{children}</main>
      </body>
    </html>
  )
}

 

 

 

[참고]

https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#layouts

 

Routing: Pages and Layouts | Next.js

Create your first page and shared layout with the App Router.

nextjs.org

 

'Frontend > Next.js' 카테고리의 다른 글

[Next.js] Linking and Navigating  (2) 2023.10.31
[Next.js] Warning: Prop `className` did not match.  (0) 2023.10.13
[Next.js] Next Overview  (3) 2023.07.31