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
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With