🔖

App Router の page.tsx の Props

2024/04/23に公開

まとめ

App Router において page.tsx は、ルートごとに作成するファイルです。

page.tsx は2種類のPropsを任意で受け付けます。

  • params: Dynamic RouteのDynamic Segmentの値を受け取る
  • searchParams: URL クエリパラメータを受け取る
import { type FC } from "react";

type Props = {
  params: {
    id: string;
  };
  searchParams: { [key: string]: string | string[] | undefined };
};

const Page: FC<Props> = (props) => {
  return (
    <>
      {"// 省略"}
    </>
  );
};

export default Page;

paramsで Dynamic Segment の値を取得できます。Dynamic Route とは、/product/[slug] のように、URL の一部が動的に変わるページのことです。Dynamic Segment とは、[slug] のように、[] で囲まれた部分のことです。

alt text
http://localhost:3000/user/12345

alt text
http://localhost:3000/user/student/12345

alt text
http://localhost:3000/product/dvd/anime

searchParamsで引数を取得できます。引数とは、URL クエリパラメータのことです。URL クエリパラメータとは、? 以降のパラメータのことです。例えば?q=test のようにq がパラメータ名でtest が値です。

alt text
http://localhost:3000/store?a=1

alt text
http://localhost:3000/store?a=1&b=2

alt text
http://localhost:3000/store?a=1&a=2

公式のドキュメントです。

https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional

Next.jsプロジェクトの作成

動作を作業するための Next.js プロジェクトを作成します。長いので、折り畳んでおきます。

新規プロジェクト作成と初期環境構築の手順詳細

プロジェクトを作成

create next-app@latestでプロジェクトを作成します。

$ pnpm create next-app@latest next-approuter-page --typescript --eslint --import-alias "@/*" --src-dir --use-pnpm --tailwind --app
$ cd next-approuter-page

Peer Dependenciesの警告を解消

Peer dependenciesの警告が出ている場合は、pnpm installを実行し、警告を解消します。

 WARN  Issues with peer dependencies found
.
├─┬ eslint-config-next 14.2.1
│ └─┬ @typescript-eslint/parser 7.2.0
│   └── ✕ unmet peer eslint@^8.56.0: found 8.0.0
└─┬ next 14.2.1
  ├── ✕ unmet peer react@^18.2.0: found 18.0.0
  └── ✕ unmet peer react-dom@^18.2.0: found 18.0.0

以下を実行することで警告が解消されます。

$ pnpm i -D eslint@^8.56.0 react@^18.2.0 react-dom@^18.2.0

不要な設定を削除し、プロジェクトを初期化します。

styles

CSSなどを管理するstylesディレクトリを作成します。globals.cssを移動します。

$ mkdir -p src/styles
$ mv src/app/globals.css src/styles/globals.css

globals.cssの内容を以下のように上書きします。

src/styles/globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;

初期ページ

app/page.tsxを上書きします。

src/app/page.tsx
import { type FC } from "react";

const Page: FC = () => {
  return (
    <div className="">
      <div className="text-lg font-bold">Home</div>
      <div>
        <span className="text-blue-500">Hello</span>
        <span className="text-red-500">World</span>
      </div>
    </div>
  );
};

export default Page;

レイアウト

app/layout.tsxを上書きします。

src/app/layout.tsx
import "@/styles/globals.css";
import { type FC } from "react";
type RootLayoutProps = {
  children: React.ReactNode;
};

export const metadata = {
  title: "Sample",
  description: "Generated by create next app",
};

const RootLayout: FC<RootLayoutProps> = (props) => {
  return (
    <html lang="ja">
      <body className="">{props.children}</body>
    </html>
  );
};

export default RootLayout;

TailwindCSSの設定

TailwindCSSの設定を上書きします。

tailwind.config.ts
import type { Config } from 'tailwindcss'

const config: Config = {
  content: [
    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
    './src/components/**/*.{js,ts,jsx,tsx,mdx}',
    './src/app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  plugins: [],
}
export default config

TypeScriptの設定

TypeScriptの設定を上書きします。

tsconfig.json
{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl" : ".",
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

スクリプトを追加

型チェックのスクリプトを追加します。

package.json
{
  "scripts": {
+   "typecheck": "tsc"
  },
}

動作確認

ローカルで動作確認します。

$ pnpm run dev

コミットして作業結果を保存しておきます。

$ git add .
$ git commit -m "feat:新規にプロジェクトを作成し, 作業環境を構築"

params(任意)

paramsを通して、Dynamic Route の Dynamic Segment の値を取得できます。Dynamic Route とは、/product/[slug] のように、URL の一部が動的に変わるページのことです。Dynamic Segment とは、[slug] のように、[] で囲まれた部分のことです。

src パス URL params
src/app/user/[slug]/page.tsx /user/12345 { slug: "12345" }
src/app/user/[...slug]/page.tsx /user/student/12345 { slug: ["student", "12345"] }
src/app/product/[category]/[item]/page.tsx /product/food/apple { category: "food", item: "apple" }

以下の例ではDynamic Segment の値を取得し、画面に表示します。

alt text
http://localhost:3000/user/12345

alt text
http://localhost:3000/user/student/12345

alt text
http://localhost:3000/product/dvd/anime

実装

コードを作成します。

$ mkdir -p src/app/user/\[slug\]
$ mkdir -p src/app/user/\[...slug\]
$ mkdir -p src/app/product/\[category\]/\[item\]
$ touch src/app/user/\[slug\]/page.tsx
$ touch src/app/user/\[...slug\]/page.tsx
$ touch src/app/product/\[category\]/\[item\]/page.tsx
src/app/user/\[slug\]/page.tsx
import { FC } from "react";

type Props = {
  params: {
    slug: string;
  };
};

const Page: FC<Props> = (props) => {
  return (
    <>
      <div className="p-5">
        <div className="p-5 bg-blue-100">
          <header className="p-5 bg-red-100 flex flex-col space-y-2">
            <h1 className="text-lg font-bold">タイトル</h1>
          </header>
          <main className="p-5 bg-green-100 flex flex-col space-y-5">
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props)}
                </pre>
              </div>
            </section>
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props.params
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props.params)}
                </pre>
              </div>
            </section>
          </main>
        </div>
      </div>
    </>
  );
};

export default Page;
src/app/user/\[...slug\]/page.tsx
import { FC } from "react";

type Props = {
  params: {
    slug: string;
  };
};

const Page: FC<Props> = (props) => {
  return (
    <>
      <div className="p-5">
        <div className="p-5 bg-blue-100">
          <header className="p-5 bg-red-100 flex flex-col space-y-2">
            <h1 className="text-lg font-bold">タイトル</h1>
          </header>
          <main className="p-5 bg-green-100 flex flex-col space-y-5">
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props)}
                </pre>
              </div>
            </section>
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props.params
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props.params)}
                </pre>
              </div>
            </section>
          </main>
        </div>
      </div>
    </>
  );
};

export default Page;
src/app/product/\[category\]/\[item\]/page.tsx
import { FC } from "react";

type Props = {
  params: {
    category: string;
    item: string;
  };
};

const Page: FC<Props> = (props) => {
  return (
    <>
      <div className="p-5">
        <div className="p-5 bg-blue-100">
          <header className="p-5 bg-red-100 flex flex-col space-y-2">
            <h1 className="text-lg font-bold">タイトル</h1>
          </header>
          <main className="p-5 bg-green-100 flex flex-col space-y-5">
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props)}
                </pre>
              </div>
            </section>
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props.params
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props.params)}
                </pre>
              </div>
            </section>
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props.params.category
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props.params.category)}
                </pre>
              </div>
            </section>
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props.params.item
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props.params.item)}
                </pre>
              </div>
            </section>
          </main>
        </div>
      </div>
    </>
  );
};

export default Page;

コミットします。

$ git add .
$ git commit -m "feat:Dynamic RouteのDynamic Segmentの値を取得"

searchParams(任意)

searchParamsを通して、引数を取得することができます。引数とは、URL クエリパラメータのことです。URL クエリパラメータとは、? 以降のパラメータのことです。例えば?q=test のようにq がパラメータ名でtest が値です。

URL searchParams
/store?a=1 { a: '1' }
/store?a=1&b=2 { a: '1', b: '2' }
/store?a=1&a=2 { a: ['1', '2'] }

以下の例では引数の値を取得し、画面に表示します。

alt text
http://localhost:3000/shop?a=1

alt text
http://localhost:3000/shop?a=1&b=2

alt text
http://localhost:3000/shop?a=1&a=2

実装

コードを作成します。

$ mkdir -p src/app/store
$ touch src/app/store/page.tsx
src/app/store/page.tsx
import { type FC } from "react";

type Props = {
  searchParams: { [key: string]: string | string[] | undefined };
};

const Page: FC<Props> = (props) => {
  return (
    <>
      <div className="p-5">
        <div className="p-5 bg-blue-100">
          <header className="p-5 bg-red-100 flex flex-col space-y-2">
            <h1 className="text-lg font-bold">タイトル</h1>
          </header>
          <main className="p-5 bg-green-100 flex flex-col space-y-5">
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props)}
                </pre>
              </div>
            </section>
            <section className="flex flex-col space-y-3 bg-yellow-100 p-5">
              <div className="flex flex-row">
                <h2 className="text-sm text-blue-800 py-2 px-3 bg-blue-100 rounded-md">
                  props.searchParams
                </h2>
              </div>
              <div className="flex flex-row">
                <pre className="w-full text-sm text-white py-2 px-3 bg-slate-800 rounded-md">
                  {JSON.stringify(props.searchParams)}
                </pre>
              </div>
            </section>
          </main>
        </div>
      </div>
    </>
  );
};

export default Page;

コミットします。

$ git add .
$ git commit -m "feat:URLクエリパラメータを取得"

さいごに

App Router の page.tsx で受け取る Props について紹介しました。

作業リポジトリは以下になります。

https://github.com/hayato94087/next-approuter-page

参考

https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional

Discussion