Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What TypeScript type should I use to reference the match object in my props?

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> {   // ... } 
like image 367
Nicolas Blanco Avatar asked Jan 07 '18 14:01

Nicolas Blanco


People also ask

Should I use type or interface for 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.

Which props should you use to match exactly the path you have for routing?

The exact prop is used to define if there is an exactly the requested path.

What is the type of React props TypeScript?

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.

How do you use params ID to match props?

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.


1 Answers

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; } 
like image 185
Nazar554 Avatar answered Oct 19 '22 22:10

Nazar554