What TypeScript type should I use to reference the match object in my props?
To add onto @Nazar554's answer above, the RouteComponentProps
type should be imported from react-router-dom
, and implemented as follows.
import {BrowserRouter as Router, Route, RouteComponentProps } from 'react-router-dom';
interface MatchParams {
name: string;
}
interface MatchProps extends RouteComponentProps<MatchParams> {
}
Further, to allow for re-usable components, the render()
function allows you to pass only what the component needs, rather than the entire RouteComponentProps
.
<Route path="/products/:name" render={( {match}: MatchProps) => (
<ProductContainer name={match.params.name} /> )} />
// Now Product container takes a `string`, rather than a `MatchProps`
// This allows us to use ProductContainer elsewhere, in a non-router setting!
const ProductContainer = ( {name}: string ) => {
return (<h1>Product Container Named: {name}</h1>)
}
You don't need to add it explicitly. You can use RouteComponentProps<P>
from @types/react-router
as a base interface of your props instead. P
is type of your match params.
import { RouteComponentProps } from 'react-router';
// example route
<Route path="/products/:name" component={ProductContainer} />
interface MatchParams {
name: string;
}
interface Props extends RouteComponentProps<MatchParams> {
}
// from typings
import * as H from "history";
export interface RouteComponentProps<P> {
match: match<P>;
location: H.Location;
history: H.History;
staticContext?: any;
}
export interface match<P> {
params: P;
isExact: boolean;
path: string;
url: string;
}