0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Next.js]App Routerにおける動的ルーティング

Posted at

App Routerでの動的ルーティング方法

以下の構成で/test/[id]の形式で動的ルーティングが可能

ディレクトリ構造

ルートディレクトリ
└apps
  └test
    └[id]
      ├page.tsx
      └layout.tsx

page.tsx

export default function Home() {
  return (
    <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <main>
        動的ルーティング可能
      </main>
    </div>
  );
}

layout.tsx

import type { Metadata } from "next";

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="en">
      <body>
        {children}
      </body>
    </html>
  );
}

/test/1にアクセス

image.png

動的ルーティングを活用したページ表示

pages.tsxのHome()関数の引数にparamsを追加し、関数内でidを使うよう修正

page.tsx

export default function Home({params}: {params: {id: string}}) {
  const { id } = params
  return (
    <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <main>
        id毎にページの要素を変更<br />
        id:{id}
      </main>
    </div>
  );
}

/test/1にアクセス

image.png

/test/2にアクセス

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?