Search code examples
reactjstypescriptdomroutertyping

TypeScript typing of url params in React Router


I try to typing url params, but get error "type {} is missing the following properties from type RouteComponentsProps<MatchParam,StaticContextn unkwon>: history, location, match How correctly typing url params in TS.

<Route exact path="/page/:id">
  <DetailsPage  /> ----> error here 
</Route>
interface MatchParams {
  id:string
}

const DetailsPage = (props: RouteComponentProps<MatchParams>) => {
 const {id} = props.match.params
}

Solution

  • when you render your component as below

    <Route exact path="/page/:id">
      <DetailsPage  /> ----> error here 
    </Route>
    

    the DetailsPage doesn't get the route props provided by react router.

    so you need to render your Route as

    <Route exact path="/page/:id" component={DetailsPage} />
    

    or

    <Route exact path="/page/:id" render={(props) =>  <DetailsPage {...props} />} />