Nice! Just a few days ago I faced this issue and solved it by modifying _app.tsx in the following way:
_app.tsx
import type { AppProps } from "next/app"; import { ReactNode } from "react"; import { NextPage } from "next"; type Page<P = {}> = NextPage<P> & { getLayout?: (page: ReactNode) => ReactNode; }; type Props = AppProps & { Component: Page; }; const App = ({ Component, pageProps }: Props) => { const getLayout = Component.getLayout ?? ((page: ReactNode) => page); return getLayout(<Component {...pageProps} />); }; export default App;
Any drawbacks to this approach against the one you propose?
Thanks for sharing!
That's just brilliant! Thanks for sharing.
I see some generics missing though — at least from next@11.1.0. I added them and it ended up being this for me:
next@11.1.0
import type { NextPage } from 'next'; import type { AppProps } from 'next/app'; import Head from 'next/head'; import type { ReactNode } from 'react'; import React from 'react'; type GetLayout = (page: ReactNode) => ReactNode; // eslint-disable-next-line @typescript-eslint/ban-types type Page<P = {}, IP = P> = NextPage<P, IP> & { getLayout?: GetLayout; }; // eslint-disable-next-line @typescript-eslint/ban-types type MyAppProps<P = {}> = AppProps<P> & { Component: Page<P>; }; const defaultGetLayout: GetLayout = (page: ReactNode): ReactNode => page; function MyApp({ Component, pageProps }: MyAppProps): JSX.Element { const getLayout = Component.getLayout ?? defaultGetLayout; return ( <> <Head> <title>My site</title> </Head> {/* eslint-disable-next-line react/jsx-props-no-spreading */} {getLayout(<Component {...pageProps} />)} </> } export default MyApp;
I added some generics based on your code.
import { NextPage } from 'next'; import type { AppProps } from 'next/app'; import { ScriptProps } from 'next/script'; import 'styles/main.scss'; type Page<P = Record<string, never>> = NextPage<P> & { Layout: (page: ScriptProps) => JSX.Element; }; type Props = AppProps & { Component: Page; }; const Noop = ({ children }: ScriptProps) => <>{children}</>; function App({ Component, pageProps }: Props) { const Layout = Component.Layout || Noop; return ( <Layout> <Component {...pageProps} /> </Layout> ); } export default App;
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice! Just a few days ago I faced this issue and solved it by modifying
_app.tsx
in the following way:Any drawbacks to this approach against the one you propose?
Thanks for sharing!
That's just brilliant! Thanks for sharing.
I see some generics missing though — at least from
next@11.1.0
. I added them and it ended up being this for me:I added some generics based on your code.