LoginSignup
13
6

More than 1 year has passed since last update.

Next.jsでネストした動的なルーティングの書き方

Last updated at Posted at 2021-01-25

Next.jsのドキュメント見たけど、自分のコードに落とし込むのが難しいよって人には参考になると思います。

バージョン

  • MacOS Catalina 10.15.7
  • Next.js 10.0.5

今回やりたいこと

以下のような感じで1や10など動的な場合のディレクトリ構成をお伝えできればと思います。
next/linkを使っての説明はなく、あくまでもディレクトリ構成に絞って書いていきます。

  • ユーザー一覧(/users)
  • ユーザー詳細(/users/1)
  • 投稿一覧(/users/1/posts)
  • 投稿詳細(/users/1/posts/10)

先に最終的なディレクトリ構成

pages
├── index.tsx
└── users
    ├── [userId]
    │   ├── index.tsx
    │   └── posts
    │       ├── [postId].tsx
    │       └── index.tsx
    └── index.tsx

やってみる

ユーザー一覧ページの作成

% mkdir src/pages/users && touch src/pages/users/index.tsx
/pages/users/index.tsx
import React from 'react';

const index: React.FC = () => {
  return <h1>/users</h1>;
};

export default index;

スクリーンショット 2021-01-25 18.13.16.png

ユーザー詳細ページの作成

% mkdir src/pages/users/\[userId] && touch src/pages/users/\[userId]/index.tsx
/pages/users/[userId]/index.tsx
import React from 'react';
import { useRouter } from 'next/router';

const index: React.FC = () => {
  const router = useRouter();
  const { userId } = router.query;
  console.log({userId});

  return <h2>/users/: {userId}</h2>;
};

export default index;

/users/1の場合

スクリーンショット 2021-01-25 18.29.23.png

/users/100の場合

スクリーンショット 2021-01-25 18.30.30.png

{userId: ${param}}というqueryが渡ってきてますね!

投稿一覧ページの作成

% mkdir src/pages/users/\[userId]/posts && touch src/pages/users/\[userId]/posts/index.tsx
/src/pages/users/\[userId]/posts/index.tsx
import React from 'react';
import { useRouter } from 'next/router';

const index: React.FC = () => {
  const router = useRouter();
  const { userId } = router.query;
  console.log({userId});

  return <h1>/users/{userId}/posts</h1>;
};

export default index;

スクリーンショット 2021-01-25 18.36.35.png

ちゃんと{userId: "1"}をpostsでも持てていますね!

投稿詳細ページの作成

% mkdir src/pages/users/\[userId]/posts && touch src/pages/users/\[userId]/posts/[postId].tsx
/src/pages/users/\[userId]/posts/[postId].tsx
import React from 'react';
import { useRouter } from 'next/router';

const index: React.FC = () => {
  const router = useRouter();
  const { userId, postId } = router.query;
  console.log({userId, postId});

  return <h1>/users/{userId}/rooms/: {postId}</h1>;
};

export default index;

スクリーンショット 2021-01-25 18.42.03.png

{userId: "1", postId: "1"}が取得できているので良さそうですね!

注意点

const {userId} = router.query;const {postId} = router.queryなどの変数名はディレクトリ名やファイル名と同じにしておかないとうまく取得できないのでご注意ください。

終わりに

参考になる方がいらっしゃいましたら幸いです

上に戻るの面倒な方用にもう一度

pages
├── index.tsx
└── users
    ├── [userId]
    │   ├── index.tsx
    │   └── posts
    │       ├── [postId].tsx
    │       └── index.tsx
    └── index.tsx
13
6
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
13
6