1
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?

More than 1 year has passed since last update.

Next14のサーバーサイドコンポーネントでURLパラメータを取得する方法

Posted at

はじめに

Next14で開発をしているときにURLパラメータを取得したかったのですが、検索をしてもフック(use~~)を使うものが多く、クライアントコンポーネントだと自分には都合がよくなかったので別の方法を紹介します。

問題

フックを利用する( == トップレベルに"use client"と書く )とクライアントコンポーネントになるが、それを避けたい。

解決策

以下のようにしてURLパラメータ(パスとクエリの両方)を取得することが可能です。

page.tsx
import { Sidebar } from "../components/layout/Sidebar";
import { Card } from "../components/ui/Card";
import { getBlogs } from "../lib/getBlogs";

export default async function SearchPage(props) {
  const {params, searchParams } = props;
  return (
    // 省略
  );
}
  • URLパスパラメータを取得したい場合
    (page.tsxの属するディレクトリが [id] のとき)

    params.id
    
  • URLクエリパラメータを取得したい場合(urlに?q=値)

    searchParams.q
    

終わりに

このpropsのことは少し前にたまたま発見していたので正直ラッキーでした。公式にも記載されてはいたので載せておきます(検索にヒットしなかった泣)。
検索の仕方がまだまだなのかなぁと思います。

参考

✨About Me✨

友達になってください!!

  • X(Twitter)

1
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
1
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?