In Next.js 13, the App Router was introduced with several exciting features, such as layouts, error boundaries, loading indicators, and more. However, some developers face challenges when managing multiple layouts at the same route level. Below, I’ll show you the best way to structure and maintain clean, convenient layouts for such scenarios.
A root layout is useful for defining global components or context providers for your entire app. However, if your app doesn’t require global configurations, you can skip this step.
// app/layout.tsx export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html> <body> <RootProviders> {children} </RootProviders> </body> </html> ); }
Suppose we need a Header and Footer for the /home and /contact pages. To achieve this, we can use Next.js Route Groups.
For example, we’ll create a route group called (marketing) and place our pages inside it. Pages like app/(marketing)/home/page.tsx and app/(marketing)/contact/page.tsx will use the app/(marketing)/layout.tsx layout.
// app/(marketing)/layout.tsx export default function MarketingLayout({ children, }: { children: React.ReactNode; }) { return ( <Providers> <Header /> <main>{children}</main> <Footer /> </Providers> ); }
Similarly, for pages like /policy and /tos, we can create a new route group called (legal) and define a specific layout for it.
// app/(legal)/layout.tsx export default function LegalLayout({ children, }: { children: React.ReactNode; }) { return ( <> <Header /> <main className="container mx-auto">{children}</main> </> ); }
Using this approach, you can:
By leveraging Route Groups and Layouts, Next.js empowers you to create modular, scalable, and maintainable architectures for your applications.
The above is the detailed content of Managing Multiple Layouts in Next.js with App Router and Route Groups. For more information, please follow other related articles on the PHP Chinese website!