Reputation: 6175
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;
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;
Upvotes: 2
Views: 5114
Reputation: 15652
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);
Upvotes: 10