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> { // ... }
And usually there will be someone who's already dabbled in TypeScript who asks me why I choose to use an interface instead of a type alias for defining the props. The short answer is that interfaces and type alias are effectively interchangeable for defining objects in TypeScript.
The exact prop is used to define if there is an exactly the requested path.
React has its own, built-in way of type checking called “prop types”. Together with TypeScript this provides a full, end-to-end type-checking experience: Compiler and run-time.
Just create constructor i.e constructor(props) {} and inside it declare the id as a state variable to the class. Pass the value of match.params.id to the id by using id: this.props.match.params.id . Now u can access the state variable anywhere in your code and hope it solves your problem.
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; }
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