2

The approach

I'm trying to get my head around Typescript and React Router. I've been struggling...

I currently get the error :

Property 'params' does not exist on type 'RouteComponentProps<{}, StaticContext, any>'.ts(2339)"`

import React from "react";
import { RouteComponentProps } from "react-router-dom";

const TopicDetail = ({ match }: { match: RouteComponentProps }) => {
  return (
    <div>
      <h3>{match.params.topicId}</h3>
                 ~~~~~~
    </div>
  );
};

export default TopicDetail;

Look ma, no errors!

I can get rid of the errors by defining my own interface, but I somehow feel it's the wrong way to do it:

import React from "react";

interface Props {
  params: any;
}
const TopicDetail = ({ match }: { match: Props }) => {
  return (
    <div>
      <h3>{match.params.topicId}</h3>
    </div>
  );
};

export default TopicDetail;

1 Answer 1

10

Defining an interface for the router params props is the recommended way to go, although you can be a bit more explicit with your interface declaration. When you declare the interface for the props for your component, you can extend the RouteComponentProps and use your specific params interface as the type variable.

For example:

import React from "react";
import { withRouter, RouteComponentProps } from "react-router-dom";

interface RouterProps { // type for `match.params`
    topicId: string; // must be type `string` since value comes from the URL
}

interface TopicDetailProps extends RouteComponentProps<RouterProps> {
    // any other props (leave empty if none)
}

const TopicDetail: React.FC<TopicDetailProps> = ({ match }) => {
    return (
        <div>
            <h3>{ match.params.topicId }</h3>
        </div>
    )
}

export default withRouter(TopicDetail);
Sign up to request clarification or add additional context in comments.

2 Comments

Ah I guess I was trying to do it in one step. Also, not realizing I needed withRouter HOC. Finally, I had to change the topicId to type string to make it work (not exactly sure why).
@skube oh yeah the string thing, forgot about that... I believe that's because the values come from the url, so they're all strings to start out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.