レイアウトの共通化

/・/about・/products/123 の3つのページを作りましたが、いまはそれぞれのページに独立した内容しか表示されていません。実際のアプリケーションでは、サイト全体で共通のヘッダ・フッタを表示したいケースが一般的です。App Routerでは、この共通枠を app/layout.tsx に書くことで、すべてのページに自動的に適用できます。

1. ルートレイアウトへのヘッダ・フッタ追加

現在の app/layout.tsx は <html> <body> と {children} だけの最小構成になっています。ここに共通ヘッダ・フッタを追加し、すべてのページで表示されるようにします。

app/layout.tsx を以下の内容に書き換えます。

import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create-next-app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="ja">
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        <header style={{ padding: "1rem", borderBottom: "1px solid #ddd" }}>
          <strong>My Next App</strong>
        </header>

        <main style={{ padding: "1rem" }}>{children}</main>

        <footer style={{ padding: "1rem", borderTop: "1px solid #ddd" }}>
          <small>&copy; 2026 My Next App</small>
        </footer>
      </body>
    </html>
  );
}

保存できたら、ブラウザで http://localhost:3000・http://localhost:3000/about・http://localhost:3000/products/123 の3つのURLを開いてみます。どのページにも同じヘッダ・フッタが表示され、真ん中の内容だけがページごとに切り替わっていれば、レイアウトの共通化ができています。

コードを解説します。

<header style={{ padding: "1rem", borderBottom: "1px solid #ddd" }}>
  <strong>My Next App</strong>
</header>

<body> の直下に <header> を配置しています。layout.tsx に書いた要素はすべてのページの外側に自動で適用されるため、app/page.tsx や app/about/page.tsx を編集しなくても全ページにヘッダが表示されます。

<main style={{ padding: "1rem" }}>{children}</main>

{children} の部分に、各ページ(page.tsx)の中身が差し込まれます。ここが「レイアウトの中の可変領域」に相当します。

<footer style={{ padding: "1rem", borderTop: "1px solid #ddd" }}>
  <small>&copy; 2026 My Next App</small>
</footer>

{children} の後にフッタを配置しています。ヘッダと同じくすべてのページで自動的に表示されます。

なお、この章ではスタイルの当て方は本題ではないため、style={{ ... }} によるインラインスタイルで済ませています。CSS ModulesやTailwind CSSといった本格的なスタイリング手法は次章のNext.jsのスタイリングで扱います。