I recently upgraded a React JavaScript project using react-router-dom V6.6.1 to TypeScript V4.9.4.
In the JavaScript Version, I had a file that wraps all the components that require access to routing (WithRouter.js):
import { useLocation, useNavigate, useParams } from 'react-router-dom'
export function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation()
let navigate = useNavigate()
let params = useParams()
return <Component {...props} params={params} navigate={navigate} location={location} />
}
return ComponentWithRouterProp
}
And at every such component, I used:
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ComponentName))
Which enabled access to the id in the URL:
websiteDomainName.com/ComponentName/componentId
by:
props.params.componentId
I need to understand how to transform the new version of WithRouter to be TypeScript compatible.
And the suggestions I found all use RouteComponentProps, which is deprecated in react-router-dom 6.6.1.
Note that useParams cannot be used directly in a class component as it is a functional component hook only.