How to access route params from react-router-dom using Typescript? Ex: `/some-route/:slug`
·
Answer a question
Taking this example route which takes a route param slug:
ROUTES.ts
export const SOME_ROUTE = `/some-route/:slug`;
And this <Switch> component that will render <Route>'s.
AllRoutes.tsx
import React from "react";
import * as ROUTES from "@routes/ROUTES";
interface AllRoutes {
}
const AllRoutes: React.FC<AllRoutes> = (props) => {
console.log("Rendering AllRoutes...");
return(
<Switch>
<Route exact path={ROUTES.SOME_ROUTE} component={MyComponent}/>
</Switch>
);
};
export default AllRoutes;
And now from the rendered component:
MyComponent.tsx
import React from "react";
import HomePage from "./HomePage";
import { RouteComponentProps } from "react-router-dom";
interface MyComponent extends RouteComponentProps {
}
const MyComponent: React.FC<MyComponent> = (props) => {
console.log("Rendering MyComponent...");
console.log(props.match.params.slug); // TRYING TO ACCESS THE `:slug` ROUTE PARAM
return(
<HomePage/>
);
};
export default MyComponent;
QUESTION
I get an error saying that the slug property does not exist. Even though it 100% exists, 'cause the value gets logged. But Typescript is unaware of it.
Do I need to manually extend the RouteComponentProps to add that props.match.params.slug property?

The routeProps (history, match, location) are present as you can see from the picture below.

Answers
With the help of the comments and these other contents:
- In ReactJS trying to get params but I get property 'id' does not exist on type '{}'
- And this article: Using typescript to write react-router 5
Here is how I'm doing it:
import React from "react";
import HomePage from "./HomePage";
import { RouteComponentProps } from "react-router-dom";
interface RouteParams {
slug: string
}
interface MyComponent extends RouteComponentProps<RouteParams> {
}
const MyComponent: React.FC<MyComponent> = (props) => {
console.log("Rendering MyComponent...");
console.log(props.match.params.slug);
return(
<HomePage/>
);
};
export default MyComponent;
useParams()
And also using the useParams() hook:
interface RouteParams {
slug: string
}
const params = useParams<RouteParams>();
更多推荐
所有评论(0)