Next Js Page Layout

Next Js Page Layout

Apply layout in next js with typescript

In pages/_app.tsx

Copied to clipboard
import type { AppProps } from 'next/app'; import type { NextPage } from 'next'; import type { ReactElement, ReactNode } from 'react'; export type NextPageWithLayout<P = Record<string, unknown>> = NextPage<P> & { getLayout?: (page: ReactElement) => ReactNode; }; type AppPropsWithLayout = AppProps & { Component: NextPageWithLayout; } const MyApp = ({ Component, pageProps }: AppPropsWithLayout) => { const getLayout = Component.getLayout ?? ((page) => page); return getLayout(<Component {...pageProps} />); }; export default MyApp;

In components/layout.tsx

Copied to clipboard
import { PropsWithChildren } from 'react'; export const Layout= ({ children }: PropsWithChildren) => { return <>{children}</>; };

In pages/page.tsx

Copied to clipboard
import { NextPageWithLayout } from './_app'; import { Layout } from '../components/layout'; const Page: NextPageWithLayout = () => { return <>...</>; }; Page.getLayout = (page) => <Layout>{page}</Layout>; export default Page;