7
6

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 5 years have passed since last update.

【React Router】URLパラメーターを取得する

Last updated at Posted at 2020-04-09

TyepeScriptでReactRouterを扱う際に、URLパラメーターを取得するところで失敗した。

App.tsx
import React from 'react';

const Characters: React.FC<{}> = (props) => {
  return (
    <>
      {props.match.params.name}
    </>
  );
}

export default Characters;

エラーメッセージは
Property 'match' does not exist on type '{ children?: ReactNode; }'. TS2339

RouteComponentPropsを用いる

matchはpropsに渡るオブジェクトに定義されてない。
そこでRouteComponentPropsとpropsの型を結合することでmatchが渡される。

App.tsx
import React from 'react';
+import { RouteComponentProps } from 'react-router';


+//interfaceの結合
+type urlProps = {} & RouteComponentProps<{name: string}>;

const Characters: React.FC<urlProps> = (props) => {
  return (
    <>
      {props.match.params.name}
    </>
  );
}

export default Characters;

URLパラメーターが渡った:grinning:

ちなみに...

VSCode上でRouteComponentPropsに左クリックしてGo to Definitionで定義ファイルを開くとmatchがプロパティにあることがわかる。

index.t.ts
export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {},C extends StaticContext = StaticContext,S = H.LocationState>
  {
    history: H.History<S>;
    location: H.Location<S>;
    match: match<Params>;
    staticContext?: C;
  }
7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?