Basic sample using typescript
Last active
May 5, 2022 06:58
-
-
Save nilsandrey/2422aaa74f1f5bf8e343b3114a282d75 to your computer and use it in GitHub Desktop.
NextJS page layouts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//... | |
import { AppProps } from 'next/app'; | |
//... | |
function App(props: AppProps) { | |
const { Component, pageProps } = props; | |
// Use the layout defined at the page level, if available | |
const getLayout = (Component as any).getLayout ?? ((page) => page); // <- typecast couldn't defined with a type holding all possible generic instances. | |
return ( | |
<> | |
{getLayout(<Component {...pageProps} />)} | |
</> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
function Layout1({ children }) { | |
return ( | |
<> | |
<main>{children}</main> | |
<footer> | |
By you | |
</footer> | |
</> | |
); | |
} | |
export default Layout1; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextPage } from 'next'; | |
import { AppProps } from 'next/app'; | |
import { ReactElement, ReactNode } from 'react'; | |
export type NextPageWithLayout<T> = NextPage<T> & { | |
getLayout?: (page: ReactElement) => ReactNode; | |
}; | |
export type AppPropsWithLayout<T> = AppProps & { | |
Component: NextPageWithLayout<T>; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextPageWithLayout } from 'lib/layouts'; | |
import Layout1 from '@components/layouts/Layout1'; | |
import React, { ReactElement } from 'react'; | |
// type MyPropsType = { ... }; | |
const Page1: NextPageWithLayout<MyPropsType> = (props) => { | |
return ( | |
<> | |
My Page content! | |
</> | |
); | |
}; | |
Page1.getLayout = function getLayout(page: ReactElement) { | |
return ( | |
<Layout1> | |
{page} | |
</Layout1> | |
) | |
} | |
export default Page1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment