In my React containers/component, which type could I use to reference the match part included by React Router DOM?
interface Props {
match: any // <= What could I use here instead of any?
}
export class ProductContainer extends React.Component<Props> {
// ...
}
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;
}
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>)
}
Simple solution
import { RouteComponentProps } from "react-router-dom";
const Container = ({ match }: RouteComponentProps<{ showId?: string}>) => {
const { showId } = match.params?.showId;//in case you need to take params
}