【Next.js】特定のページのみ共通のコンポーネントを描画する方法

2021-09-22

公式サイトに思いっきり書いてありました…全然知らなかった。

Per-Page Layouts

// pages/index.tsx

import type { ReactElement } from "react";
import Layout from "../components/layout";
import NestedLayout from "../components/nested-layout";

export default function Page() {
  return {
    /** Your content */
  };
}

Page.getLayout = function getLayout(page: ReactElement) {
  return (
    <Layout>
      <NestedLayout>{page}</NestedLayout>
    </Layout>
  );
};
// pages/_app.tsx

import type { ReactElement, ReactNode } from "react";
import type { NextPage } from "next";
import type { AppProps } from "next/app";

type NextPageWithLayout = NextPage & {
  getLayout?: (page: ReactElement) => ReactNode;
};

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout;
};

export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout ?? ((page) => page);

  return getLayout(<Component {...pageProps} />);
}

動作未確認ですが、公式のドキュメントなので問題なく動くと思います。

Gatsby.js のバージョン 4 だとこれに相当する機能がおそらく提供されていないような…バージョン 3 まではプラグインがあったんですが。