MENU
From 'withRouter' to Hooks
The withRouter() higher-order component no longer exists – there is no direct replacement HOC. Instead, a component that needs routing information should simply be a function component that calls useLocation(), useParams(), or useNavigate() directly.
Before (React Router 5, no longer works): withRouter used to pass updated match, location, and history props to the wrapped class component whenever it rendered.
// OLD - withRouter no longer exists
import React from "react";
import { withRouter } from "react-router-dom";
class ShowTheLocation extends React.Component {
render() {
const { location } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
export default withRouter(ShowTheLocation);After: drop the class and the HOC, and call the hook directly in a function component.
import React from "react";
import { useLocation } from "react-router";
// A simple component that shows the pathname of the current location
function ShowTheLocation() {
let location = useLocation();
return <div>You are now at {location.pathname}</div>;
}
export default ShowTheLocation;