TypeScript | React Router Explicit Match Type

(Last edited: October 29, 2019)

One can correctly type the match of a component connected with withRouter or component names passed directly in the Route component by using the RouteComponentProps interface defined in 'react-router-dom'.

import { createBrowserHistory } from 'history'
import React, { FC, useEffect } from 'react'
import { render } from 'react-dom'
import { RouteComponentProps, Route, Router, Switch } from 'react-router-dom'

import './styles.css'

const browserHistory = createBrowserHistory()
const objectIdParameter = 'objectId'

interface IHomeProps  extends RouteComponentProps<{ [key in typeof objectIdParameter]: string }> {}
const Home: FC<IHomeProps> = ({ match }) => (
  <div>Home Page with id {match.params.objectId}</div>
)

const App: FC = () => {
  useEffect(() => {
    browserHistory.push('/42')
  }, [])

  return (
    <Router history={browserHistory}>
      <Switch>
        <Route component={Home} path={`/:${objectIdParameter}`} />
      </Switch>
    </Router>
  )
}

const rootElement = document.getElementById('root')
render(<App />, rootElement)

The above example can be seen in action in the below CodeSandbox:


© 2022, built with Gatsby. Subscribe via RSS.
Crafted by John Darryl Pelingo
. All rights reserved.