19
5

More than 1 year has passed since last update.

【React】Next.js13以降でURLのクエリパラメーターを取得する方法

Last updated at Posted at 2023-05-05

概要

Next.jsでURLのクエリパラメータを取得する場合、Next.js useRouterで、query stringを取得するの記事にある通り、useRouterを使用する方法が検索すると出てくるかと思います。
ただ、Next.js13のApp Routerを使用している状態で同様の実装を行うとパラメータが取得できず、どのように実装すれば良いのかというのを今回メモ書きします。

前提

  • Next.jsのバージョンは13.3で動作確認しました。
  • App Routerの使用を前提としています。

対応

stackoverflowの記事、NextRouter was not mounted Next.JSにある通り13からuseRouterの仕様が変更になったようです。パラメータについてはuseSearchParamsを使用して、取得する必要があるそうです。
useSearchParamsの仕様の詳細については公式のドキュメントuseSearchParams API Referenceを参照ください。

実装サンプル

useSearchParamsを使用して、URLのクエリパラメータを取得する実装サンプルを、以下の通り記載します。

"use client";

import { useSearchParams } from "next/navigation";

export default function SampleParamComponent() {
  const searchParams = useSearchParams();
  const id = searchParams.get("sample_id");
  const name = searchParams.get("sample_name");

  return (
    <>
      <div>{id}</div>
      <div>{name}</div>
    </>
  );
}
19
5
2

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
19
5