0

I'm using react router and typescript to get the id variable from a route to use in a component and typescript is complaining that:

Type '{}' is missing the following properties from type 'match': params, isExact, path, url

Heres my code (App.tsx):

<Route path='/posts/:id'>
  <Post />
</Route>

Post.tsx :

import React from 'react';
import { match } from 'react-router';

interface Identifiable {
  id: string
  params: string,
  isExact: string,
  path: string,
  url: string,
}

const Post = (mathedRoute: match<Identifiable>) => {
  return <h1>{mathedRoute.params.id}</h1>
}

export default Post;

Thanks in advance for your help.

JoshuaRDBrown
  • 343
  • 5
  • 12

2 Answers2

1

In order to extract the match, you need to render the component, rather than pass it as a child.

<Route path='/posts/:id' render={({match}) => <Post match={match} />} />

Typescript might still complain about it, in which case you'd need to import RouteComponentProps from "react-router-dom" and possibly extend it.

However! The good news is, react router hooks exist!

I'd suggest playing around with them, especially the useRouteMatch and useParams hooks.

tachko
  • 161
  • 1
  • 8
0

You could use standard way:

import React from 'react';
import { Route, RouteComponentProps, Switch } from 'react-router-dom';

interface PostParams {
    id: string;
}

function Post(props: RouteComponentProps<PostParams>) {
    return <>{props.match.params.id}</>;
}

export function App() {
    return (
        <Switch>
            <Route path='/posts/:id' component={Post}/>
        </Switch>
    );
}

or hook way:

import React from 'react';
import { Route, Switch, useParams } from 'react-router-dom';

interface PostParams {
    id: string;
}

function Post() {
    const { id } = useParams<PostParams>();
    return <>{id}</>;
}

export function App() {
    return (
        <Switch>
            <Route path='/posts/:id'>
                <Post/>
            </Route>
        </Switch>
    );
}

In your code you are trying to mix them together.
reed more about react router v5

kajkal
  • 504
  • 5
  • 8
  • Thanks for your reply. Doing this still gives me this error when trying to render the component: Type '{}' is missing the following properties from type 'RouteComponentProps': history, location, match – JoshuaRDBrown Jun 21 '20 at 17:43
  • Just figured it out, seems you have to use instead for some reason :( – JoshuaRDBrown Jun 21 '20 at 17:46
  • Please check [this link](https://reacttraining.com/blog/react-router-v5-1/), i think that it will help :) – kajkal Jun 21 '20 at 17:50
  • In short: `Route` component is unable to pass `RouteComponentProps` to component defined as its child. You either have to use `Route` component with `render`, `children`, or `component` props or use `useParams` hook. – kajkal Jun 21 '20 at 23:58