18
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Next.jsでパスパラメータを取得する方法

Posted at

概要

フロントエンドのフレームワークを使うと、パスパラメータを使用したくなる時があります。パスパラメータについては、パスパラメータとクエリパラメータの違いを参照頂きたいのですが、URLパスに変数の値を指定する手法です。これをNext.jsで実現したい場合、どうすれば良いのか今回書きます。

どうすれば良いのか

ドキュメントの動的なルーティングに書いてあるとおり、パスパラメータを設定したいパスのjsファイル名に[パスパラメータ名].jsを指定することで、パラメータの取得をそのjs内で行うことができます。言葉だけだと、ピンと来ないかもしれないので以下にサンプルを示します。

実装サンプル

今回は記事投稿を例にします。パスパラメータに投稿id(post_id)を設定し、これを取得するやり方を書きます。

<ファイルの配置>
pages/postの配下に[post_id].jsを配置します。
スクリーンショット 2020-11-27 0.19.43.png

<[post_id].jsの内容>
router.queryでパスパラメータ名(post_id)を指定することで取得できます。

[post_id].js
import { useRouter } from "next/router";
import Header from "../../components/common/Header";
import PostRefer from "../../components/post/PostRefer";

const Index = () => {
  const router = useRouter();
  // パスパラメータから値を取得
  const { post_id } = router.query;
  return (
    <div>
      <Header />
      <PostRefer postId={post_id} />
    </div>
  );
};

export default Index;

<このページへのアクセス>
http://localhost:3000/post/[post_id]へアクセスすると、パスパラメータを取得するページにアクセスします。
スクリーンショット 2020-11-27 1.50.17.png

18
8
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
18
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?