Skip to content

Instantly share code, notes, and snippets.

@mhaecal
Last active July 23, 2022 09:05
Show Gist options
  • Save mhaecal/4968833d631891be30fad78f66442264 to your computer and use it in GitHub Desktop.
Save mhaecal/4968833d631891be30fad78f66442264 to your computer and use it in GitHub Desktop.
Nextjs Multiple Layouts
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import type { NextPage } from 'next'
import type { ReactElement, ReactNode } from 'react'
export type NextPageWithLayout = NextPage & {
getLayout?: (page: ReactElement) => ReactNode
}
type AppPropsWithLayout = AppProps & {
Component: NextPageWithLayout
}
function MyApp({ Component, pageProps }: AppPropsWithLayout) {
const getLayout = Component.getLayout ?? ((page) => page)
return getLayout(<Component {...pageProps} />)
}
export default MyApp
import MainLayout from '../components/layouts/MainLayout'
import type { ReactElement } from 'react'
import type { NextPageWithLayout } from './_app'
function About() {
return <p>Hello this is about page with main layout!</p>
}
About.getLayout = function getLayout(page: ReactElement) {
return <MainLayout>{page}</MainLayout>
}
export default About
import type { ReactChild } from 'react'
function AdminLayout({ children }: { children: ReactChild }) {
return (
<>
<h1>Admin Layout</h1>
<main>{children}</main>
</>
)
}
export default AdminLayout
import type { ReactChild } from 'react'
function MainLayout({ children }: { children: ReactChild }) {
return (
<>
<h1>Main Layout</h1>
<main>{children}</main>
</>
)
}
export default MainLayout
import AdminLayout from '../../components/layouts/AdminLayout'
import type { ReactElement } from 'react'
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<p>Hello this is dashboard page with admin layout!</p>
</div>
)
}
Dashboard.getLayout = function getLayout(page: ReactElement) {
return <AdminLayout>{page}</AdminLayout>
}
export default Dashboard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment