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?

More than 1 year has passed since last update.

Next.jsでuseRouterフックを使用して現在のページのパス情報にアクセスする方法。

Posted at

はじめに

Next.jsでは、useRouterフックを使用して現在のページのパス情報にアクセスすることができる。window.location.pathnameの代わりに、useRouterフックを利用することで、サーバーサイドレンダリング環境での動作を問題なく保証することで、エラーにならない。

useRouterを使った書き方の例は以下の通り。

①現在アクセスしているURLを取得する例

import { useRouter } from 'next/router';

const Footer = () => {
  const router = useRouter();

  const GetHouseColor = () => {
    if (router.pathname === '/home') {
      return 'text-orange-400';
    } else {
      return 'text-black';
    }
  };

このコードでは、useRouterフックをインポートし、routerオブジェクトを取得している。
その後、router.pathnameを使って現在のページのパス情報にアクセスし、/homeのページを表示している場合を指定しています。この方法で、サーバーサイドでの実行でも問題が発生せず、エラーにならない。

pathnameとは

pathnameは、URLの一部で、ドメイン名(またはIPアドレス)の後に続く、リソースへのパスを示す部分。
要するに、ウェブサイトの各ページを特定するために使用されるパスのこと。
例えば、以下のURLがある場合、

https://example.com/blog/post-1

このURLのpathname/blog/post-1 ということになる。
このpathnameを使って、現在表示されているページがどのページであるかを判断することが可能。

②現在アクセスしているURLの動的パラメータを取得する例

このコードは、Reactのフックを使用して、レシピの取得と状態管理を行うコンポーネント。
useRouterを使用して、URLからIDを取得し、axiosを使用してAPIからレシピの情報を取得する。
レシピ情報は、useStateを使用して、stateとして管理する。

コード

const router = useRouter()
const { id } = router.query
const [recipe, setRecipe] = useState<Recipe | undefined>(undefined)

// レシピの取得
const getRecipe = useCallback(() => {
  axios
    .get<Recipe>('http://localhost:8000/recipes' + id)
    .then((response) => {
      setRecipe(response.data)
      console.log('レシピの取得に成功しました', response.data)
    })
    .catch((error) => {
      console.log('レシピの取得に失敗しました', error)
    })
}, [id])
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?