0
0
NextJSframework~5 mins

Root layout (required) in NextJS

Choose your learning style9 modes available
Introduction

The root layout is the main wrapper for all pages in a Next.js app. It helps keep common parts like headers or footers consistent everywhere.

You want a consistent header and footer on every page.
You need to add global styles or fonts once for the whole app.
You want to set metadata like page title or language for all pages.
You want to wrap all pages with a context provider or theme.
You want to add a navigation menu that appears on every page.
Syntax
NextJS
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {/* Common UI like header */}
        {children}
        {/* Common UI like footer */}
      </body>
    </html>
  )
}

The children prop represents the page content inside the layout.

The root layout must be named layout.js or layout.tsx and placed in the app/ folder.

Examples
This root layout adds a header and footer around every page.
NextJS
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <header>My Site Header</header>
        {children}
        <footer>My Site Footer</footer>
      </body>
    </html>
  )
}
A minimal root layout that just wraps pages in a <main> tag.
NextJS
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <main>{children}</main>
      </body>
    </html>
  )
}
Sample Program

This root layout adds a styled header and footer around the page content. Every page will show the same header and footer automatically.

NextJS
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <header style={{ padding: '1rem', backgroundColor: '#eee' }}>
          <h1>Welcome to My Next.js App</h1>
        </header>
        <main style={{ padding: '1rem' }}>
          {children}
        </main>
        <footer style={{ padding: '1rem', backgroundColor: '#eee', marginTop: '2rem' }}>
          <p>Ā© 2024 My Next.js App</p>
        </footer>
      </body>
    </html>
  )
}
OutputSuccess
Important Notes

The root layout wraps all pages, so changes here affect the whole app.

Use semantic HTML tags like <header>, <main>, and <footer> for better accessibility.

Remember to set the lang attribute on the <html> tag for screen readers and SEO.

Summary

The root layout is the main wrapper for all pages in Next.js.

It helps keep common UI and settings consistent across the app.

Always place it in the app/ folder as layout.js or layout.tsx.