LoginSignup
9
7

More than 1 year has passed since last update.

React Router urlパラメータ 取得 & 型指定(TypeScript)

Posted at

はじめに

React Router で指定したルーティングのパラメータを取得方法に関して学習したのでまとめてみました。
*学習ノート
*ドキュメントに全ては載っています。

コンポーネントでpropsでURLの一部の情報を受け取る

ルーティングにマッチした際に表示するコンポーネントでpropsとしてURLの一部の情報を受け取ることができる。

Routing.jsx
import React from 'react'
import { BrowserRouter as Router, Switch } from 'react-router-dom'

// page
import Top from './views/pages/top/Top'
import { Child } from './views/pages/Child'

import { hot } from 'react-hot-loader'

const Routing = () => {
  return (
    <Router>
      <Switch>
        <div>
          <Route exact path="/" component={Top} />
          <Route exact path="/users/:id" component={Child} />
        </div>
      </Switch>
    </Router>
  )
}

export default hot(module)(Routing)

Child.jsx
import React from 'react'

export const Child = (props) => {
  console.log(props)
  return (
    <div>
      {props.match.params.id} => :id部分を表示することができる
    </div>
  )
}

*Topコンポーネントはあまり重要じゃないので記載していません

コンソールログの結果

users/1で遷移した場合
Child.jsxで設置したconsole.logをみてみると以下のような結果が出ます。

{history: {…}, location: {…}, match: {…}, staticContext: undefined}
history:
 ~~~~省略~~~~
 location: {pathname: "/users/1", search: "", hash: "", state: undefined, key: "*****"}
 ~~~~省略~~~~
 __proto__: Object
location:
 ~~~~省略~~~~
 pathname: "/users/1"
 search: ""
 state: undefined
 __proto__: Object
match:
 isExact: true
 params: {id: "1"}
 path: "/users/:id"
 url: "/replies/1"

コンポーネントでpropsでURLの一部の情報を受け取る(型指定)

先ほどのコードに、型指定を追加したいと思います。

型指定を行う際にはreact-routerの型定義がされている@types/react-router-domをインストールする必要がある。

npm install @types/react-router-dom
or
yarn add @types/react-router-dom

そして、ChildコンポーネントにてRouteComponentPropsをインポートし、パラメータの型定義を追加する。(今回だと:idなのでid: stringとしている)

Child.tsx
import React, { useEffect } from 'react'
import { RouteComponentProps } from 'react-router-dom'

interface Props extends RouteComponentProps<{ id: string }>{}

export const Child = (props: Props) => {
  console.log(props)
  return (
    <div>
      {props.match.params.id} => :id部分を表示することができる
    </div>
  )
}

useParamsを使用して取得する*(React v16.8以上)

useParamsとは

useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current Route
Google翻訳: useParamsは、URLパラメータのキーと値のペアのオブジェクトを返します。現在ののmatch.paramsにアクセスするために使用します
引用: https://reactrouter.com/web/api/Hooks/useparams

こちらはReactのバージョンが16.8以上の場合使用することが可能です。
useParamsを使うと、URLのパラメータを取得できる&型指定も楽にできました。
パラーメータ部分のみの取得を行いたい場合はこちらでもいいのかなという所感です。

Child.tsx
import React, { useEffect } from 'react'
import { useParams } from 'react-router-dom'

export const Child = () => {
  const urlParams = useParams<{ id: string }>()
  console.log(urlParams.id) => :idの値を表示することができる
  return (
    <div>
      {urlParams.id} => :id部分を表示することができる
    </div>
  )
}

終わりに

URLの情報を取得にあたって、複数方法があることを知りました。
正直どれがベストという答えを出すことはできませんでした。

ディープな使い方をする際は〜の方法で行った方がいいとかあると思います。
バックエンドを含めて型定義したい場合はこうするなどまだまだ学習するポイントはありそうです。

参考文献

React Router web用 ドキュメント
React Router ドキュメント useParamsについて
サルでもわかったreact-router v5【サンプルの読解と実践】

9
7
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
9
7