DEV Community

Discussion on: Next.js Per-Page Layouts and TypeScript

Collapse
 
mauriciorobayo profile image
Mauricio Robayo • Edited

Nice! Just a few days ago I faced this issue and solved it by modifying _app.tsx in the following way:

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;
Enter fullscreen mode Exit fullscreen mode

Any drawbacks to this approach against the one you propose?

Thanks for sharing!

Collapse
 
carloschida profile image
Carlos Chida

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:

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;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
leozengtao profile image
Leo Zeng • Edited

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;
Enter fullscreen mode Exit fullscreen mode