Skip to content

Instantly share code, notes, and snippets.

@nilsandrey
Last active May 5, 2022 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilsandrey/2422aaa74f1f5bf8e343b3114a282d75 to your computer and use it in GitHub Desktop.
Save nilsandrey/2422aaa74f1f5bf8e343b3114a282d75 to your computer and use it in GitHub Desktop.
NextJS page layouts
//...
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} />)}
</>
);
}
import React from 'react';
function Layout1({ children }) {
return (
<>
<main>{children}</main>
<footer>
By you
</footer>
</>
);
}
export default Layout1;
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>;
};

Basic sample using typescript

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