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.

【React】アクセスしている URL の情報を取得できるuseRouteMatchフック

Posted at

本記事では、React Routerのフックの1つである、useRouteMatchについてまとめています。

useRouteMatchフックを利用するとアクセスしているURLの情報を取得することができます。取得した値を利用して Route コンポーネントの設定に利用することも可能。

useRouteMatch が返すオブジェクト

useRouteMatchが返すオブジェクトには、マッチングに関する情報が含まれる。
React Routerが提供する match オブジェクトを返す。matchオブジェクトは以下の情報を持つ。

オブジェクト
path ルートパス。マッチングに使用されるパターンの文字列。
url 実際のURLの一部。リンクの作成やリダイレクトなどに役立つ。
isExact URL がルートパスと一致するか、マッチングが厳密に行われたかどうかを示すブール値。
params ルートのパス内で定義されたパラメーターのキーと値のオブジェクト。

例:

// URLが "/user/123" の場合
let match = useRouteMatch("/user/:id");

// match オブジェクト:
{
  path: "/user/:id",
  url: "/user/123",
  isExact: true,
  params: { id: "123" }
}

パスなしで使用した場合

引数なしでuseRouteMatch()を呼び出すと、現在のルートのマッチング情報を取得できる。これは、Routeコンポーネントのrenderプロップや子コンポーネント内で現在のマッチング情報を取得したい場合などに役立つ。

例:

const MyComponent = () => {
  const match = useRouteMatch();
  // 現在のルートのURLを取得
  return (
    <div>
        <Link to={`${match.url}/components`}>Components</Link>
    </div>
   )
}

参考リンク
https://reffect.co.jp/react/react-router/
https://qiita.com/h-yoshikawa44/items/aa78b6c7cd1ef43549bf#useroutematch
http://fumiononaka.com/Business/html5/FN2005004.html

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?