If you are using a class, there is no withRouter
any more.
What happened to withRouter? I need it!
This question usually stems from the fact that you're using React class components, which don't support hooks. In React Router v6, we fully embraced hooks and use them to share all the router's internal state. But that doesn't mean you can't use the router. Assuming you can actually use hooks (you're on React 16.8+), you just need a wrapper.
So, you'll need to create your own wrapper, as shown in the docs.
Here is my implementation, a little more easy-to-use than doc example:
import React from 'react';
import {useLocation, useNavigate, useParams} from 'react-router-dom';
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return <Component {...props} {...{location, navigate, params}} />;
}
return ComponentWithRouterProp;
}
export default withRouter;
Use (when exporting your component):
export default withRouter(Link);
More Use-cases Example -> for other people that came here:
Example of loading batch of components wrapped with withRouter, or just your Link component.
const routingList = [{title: 'Home', search: '/', component: Home, icon: 'fa-home'},{...}]
<Routes>
{
routingList.map((routing) => {
let Child = routing.component;
return <Route key={routing.search} path={routing.search} element={<Child {...routing.compProps} />} />;
})
}
<Route path="/link" element={<Link />} />
</Routes>
And, in your component, you can use:
this.props.location.pathname
this.props.params.paramName