React Use RouteComponentProps - Type '{}' is missing the following properties from type 'Readonly<RouteComponentProps<{}

Manoj Sethi picture Manoj Sethi · May 6, 2019 · Viewed 9.6k times · Source

I am using React with Typescript and needs to use the history for that I need to have interface of RouteComponentProps

export default class Routes extends Component<RouteComponentProps, any> {
  render() {
   return (
    <div>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/login" component={Login} />
        <ProtectedRoute exact path="/admin" component={Admin} />
      </Switch>
    </div>
  );
 }}

When I use the props interface as RouteComponentProps it gives me error at below code.

class App extends Component {
  render() {
   return (
     <Provider>
       <React.Fragment>
         <Navbar />
         <Routes />
       </React.Fragment>
     </Provider>
 );
}
}

Error comes when I try to use my Route Component. The error says

Type '{}' is missing the following properties from type 'Readonly>': history, location, match TS2739

Kindly help in resolving this issue

Answer

Juraj Kocan picture Juraj Kocan · May 6, 2019

you have to pass these props to your component.

ofc you dont want to pass it in App component. Just wrap it with hoc from react-router lib)

high order component "withRouter" will do the job

import { RouteComponentProps, withRouter } from 'react-router';    
class Routes extends React.Component<RouteComponentProps, any> {

  public render() {
    return (
      <div>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/login" component={Login} />
          <ProtectedRoute exact path="/admin" component={Admin} />
        </Switch>
      </div>
    );
  }
}

export default withRouter(Routes);