Logo

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);

How It Works

  1. withRouter(MyComponent) returns a new component that subscribes to route changes.
  2. It injects three props: history, location, and match into MyComponent.
  3. 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 the history instance 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 a render prop which receives history, location, and match.
  • You can then access history.push() right inside that render function.

4. Summary of Approaches

  1. withRouter: Wrap a component (class or function) with withRouter to inject history.
  2. useHistory (hooks-based): In functional components, call useHistory() to obtain history and navigate.
  3. <Route render />: Use <Route render> to access history, location, and match within inline render logic.

Additional Tips and Best Practices

  1. Don’t Overuse Programmatic Navigation
    • Prefer declarative navigation with <Link> or <NavLink> for standard user flows. Reserve history.push() for special cases (e.g., post-submission redirects, protected routes, or error handling).
  2. Ensure React Router v4 or v5
    • The <Route render> approach, withRouter, and useHistory all require React Router v4 or higher.
    • useHistory specifically is from React Router v5.1+, but it’s backward-compatible with many v4 setups if you install the correct version.
  3. 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:

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 withRouter in class components or function components to inject history.
  • In hooks-based function components, prefer useHistory.
  • Alternatively, leverage <Route render> to get history, location, and match in 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.

CONTRIBUTOR
TechGrind