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:
As you can see, this still has problems.
Implementing React Router v6 with code splitting in a React Typescript project. React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.
In order to useParams you need to implement a generic for useParams. Building on my example above, I need to type the id . type QuizParams = { id: string; }; // In order to implement that, I'd apply my type to the hook when calling it. const { id } = useParams<QuizParams>();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With