The withRouter higher-order component in React Router v5 injects the history, location, and match props into a component that is not directly rendered by a <Route>.
Purpose:
It gives access to routing props (history, location, match) in components that are not route components.
When to use it:
When you need routing props in a component that is not rendered by a <Route> (e.g., a deeply nested child or a component outside the router).
Example:
import { withRouter } from 'react-router-dom';
function MyComponent({ history, location, match }) {
// Can now use routing props
return <button onClick={() => history.push('/')}>Home</button>;
}
export default withRouter(MyComponent);