Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 737
Manoj Sethi Avatar asked May 06 '19 09:05

Manoj Sethi


People also ask

Is missing the following properties from type?

The error "Type is missing the following properties from type" occurs when the type we assign to a variable is missing some of the properties the actual type of the variable expects. To solve the error, make sure to specify all of the required properties on the object. Here are some examples of how the error occurs.

What is RouteComponentProps?

RouteComponentProps looks to be a Typescript interface definition of react-router-dom's route-props. The RouteComponentProps prop-types definition may've been part of react-router-dom but isn't currently exported. I found the Typescript export in Definitely Typed.

How do I import useHistory?

Through the history object, we can access and manipulate the current state of the browser history. All we need to do is to call the useHistory hook inside a functional component: import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirect = () => { history.


1 Answers

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);
like image 112
Juraj Kocan Avatar answered Oct 12 '22 07:10

Juraj Kocan