How to push to History in React Router v4?
React Router v4 introduced a new, more declarative way to handle navigation. However, you still need programmatic navigation in certain cases (e.g., after a successful form submission). To do this, you’ll often work with the history object to push new routes. Below are several ways to accomplish this in React Router v4.
1. Using the withRouter Higher-Order Component
If you have a class component or a functional component that needs direct access to the history object, you can wrap it with withRouter. This will inject history, location, and match props into your component.
import React from 'react';
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
handleClick = () => {
// Programmatically navigate to "/about"
this.props.history.push('/about');
};
render() {
return (
<button onClick={this.handleClick}>
Go to About Page
</button>
);
}
}
// Wrap with 'withRouter' to get 'history' prop
export default withRouter(MyComponent);
Recommended Courses
How It Works
withRouter(MyComponent)returns a new component that subscribes to route changes.- It injects three props:
history,location, andmatchintoMyComponent. - You can then call
this.props.history.push(...)to change the route programmatically.
2. Using the useHistory Hook (For Functional Components)
If you’re using React Hooks, you can leverage the useHistory hook introduced in React Router v5.1. It also works in v4 if you’ve upgraded to a version that includes hooks (i.e., React Router v5.x is fully compatible with v4’s concepts, with additional features).
import React from 'react';
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleClick = () => {
history.push('/about');
};
return (
<button onClick={handleClick}>
Go to About Page
</button>
);
}
export default MyComponent;
How It Works
useHistory()returns thehistoryinstance used by React Router.- You can call
history.push('/somePath')to navigate to a new route.
3. Accessing history via <Route> Render Props
Another pattern is to use the render prop approach on a <Route>, which provides you with the history object:
import React from 'react';
import { Route } from 'react-router-dom';
function App() {
return (
<Route
path="/"
render={({ history }) => (
<button onClick={() => history.push('/about')}>
Go to About
</button>
)}
/>
);
}
export default App;
How It Works
- The
<Route>component can take arenderprop which receiveshistory,location, andmatch. - You can then access
history.push()right inside that render function.
4. Summary of Approaches
withRouter: Wrap a component (class or function) withwithRouterto injecthistory.useHistory(hooks-based): In functional components, calluseHistory()to obtainhistoryand navigate.<Route render />: Use<Route render>to accesshistory,location, andmatchwithin inline render logic.
Additional Tips and Best Practices
- Don’t Overuse Programmatic Navigation
- Prefer declarative navigation with
<Link>or<NavLink>for standard user flows. Reservehistory.push()for special cases (e.g., post-submission redirects, protected routes, or error handling).
- Prefer declarative navigation with
- Ensure React Router v4 or v5
- The
<Route render>approach,withRouter, anduseHistoryall require React Router v4 or higher. useHistoryspecifically is from React Router v5.1+, but it’s backward-compatible with many v4 setups if you install the correct version.
- The
- Handle Edge Cases
- When using programmatic navigation after API calls or asynchronous operations, ensure your component is still mounted (e.g., the user hasn’t navigated away).
- For protected routes, consider using a higher-order component or custom hooks for authentication checks.
Leveling Up Your React Router Skills
If you want to master not just routing but also more advanced concepts—like code splitting, advanced patterns, or system design for large-scale apps—here are a few resources from DesignGurus.io:
- Grokking the Coding Interview: Patterns for Coding Questions: Ideal for improving algorithmic thinking and data structures, which complements building robust front-end applications.
- Grokking JavaScript Fundamentals: Solidify your JavaScript knowledge, essential for getting the most out of React.
- System Design Primer The Ultimate Guide: Excellent resource if you’re also exploring back-end architecture or planning large-scale features.
For hands-on feedback, try Coding Mock Interviews with ex-FAANG engineers who can guide you through real-world scenarios and interview-style challenges.
Conclusion
To push to history in React Router v4:
- Use
withRouterin class components or function components to injecthistory. - In hooks-based function components, prefer
useHistory. - Alternatively, leverage
<Route render>to gethistory,location, andmatchin a render prop.
This pattern is fundamental for performing redirects or conditional navigations based on user actions, form submissions, or dynamic logic in your React applications.