How to push to history in React Router v4?

Sometimes, we want to push to History in React Router v4.

In this article, we’ll look at how to push to History in React Router v4.

How to push to History in React Router v4?

To push to History in React Router v4, we can use the createBrowserHistory method to return the history object.

Then we can call push on the history object.

For instance, we write

history.js

import {
  createBrowserHistory
} from 'history';

export default createBrowserHistory();

to add a module that returns the history object returned from createBrowserHistory.

Then we add some routes with

app.js

import { Router, Route, Link } from 'react-router-dom';
import history from './history';

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
        </ul>
        <Route exact path="/" component={HomePage} />
        <Route path="/login" component={LoginPage} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('root'),
);

And then we can navigate in our code with

actionCreators.js

import history from '../history';

export const login = (credentials) => {
  return async (dispatch) => {
    await loginRemotely(credentials)
    //...
    history.push('/');
  };
}

We call history.push to push to the history and navigate by importing the history object with the import statement and call push on it.

Conclusion

To push to History in React Router v4, we can use the createBrowserHistory method to return the history object.

Then we can call push on the history object.