What to declare react-router argument as in TypeScript

Viewed 16728

I'm trying to get set up with react-router using Typescript in a way which accepts a parameter.

In my render element I have

<Route path="/show/:id" component={TestComp} />

And I define TestComp as

const TestComp = ({ match }) => (
    <div>
        <h2>Showing specified ID: {match.params.id}</h2>
    </div>
)

However, VS Code underlines the match parameter (in the declaration of TestComp) and tells me

Binding element 'match' implicitly has an 'any' type.

and it fails to compile.

Can anyone tell me as what type match should be declared? I've tried RouteProps but that doesn't work either. Looking in the index.d.ts, I think it's defined as match<P> but I'm not sure how to declare a parameter as being of a generic type.

UPDATE
Based on the comments to @TarasPolovyi's answer, I've added the following:

enter image description here

As you can see, this still has problems.

6 Answers

If you are using react-router v4 then import RouteComponentProps from react-router-dom and use type RouteComponentProps<RouteInfo> - the argument name must be a match

If you are using Typescript and React Router V 4.0 then the syntax is different. You declare your Route as following:

<Route path="/home/:topic?" render={() => {
   return this.renderView(<ContentHolder />);
}} />

Then the Component is declared as following:

interface RouteInfo {
    topic: string;
}

interface ComponentProps extends RouteComponentProps<RouteInfo> {
}

class ContentHolder extends Component<ComponentProps> {

    render() {
        return (
            <Content>
                <h1 className="page-title">{this.props.match.params.topic}</h1>
            </Content>
        );
    };
};

export default withRouter(ContentHolder);

Then inside your this.props.match.params you get fully IntelliSense in both VS Code and IntelliJ

You should install a package @types/react-router, which has types declaration for react-router. It contains an interface match<P>, so you can describe your property type using it.

To specify prop type as RouteComponentProps<T>, then you can access with match.params.your_prop

<Route path="/show/:showId" component={TestComp} / >

<Link to={'/show/1'}>CLICK HERE</Link>

// or, use string interpolation with variable as below
<Link to={`/show/${id}`}>CLICK HERE</Link>
import React from "react";
import { RouteComponentProps } from "react-router-dom";

type Props = {
    showId: string;
}

const TestComp= ({ match }: RouteComponentProps<Props>) => {
    console.log(match.params.showId);
}

There are 2 ways

const Container = ({ match }: RouteComponentProps<{ showId: string}>) => {
 const { showId} = match.params.showId;
}

or

const Container = () => {
  const { showId} = useParams<{ showId: string }>();
}
Related