How to get history on react-router v4?

storm_buster picture storm_buster · Mar 8, 2017 · Viewed 134.4k times · Source

I having some little issue migrating from React-Router v3 to v4. in v3 I was able to do this anywhere:

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');

How do I achieve this in v4.

I know that I could use, the hoc withRouter, react context, or event router props when you are in a Component. but it is not the case for me.

I am looking for the equivalence of NavigatingOutsideOfComponents in v4

Answer

Paul S picture Paul S · Mar 8, 2017

You just need to have a module that exports a history object. Then you would import that object throughout your project.

// history.js
import { createBrowserHistory } from 'history'

export default createBrowserHistory({
  /* pass a configuration object here if needed */
})

Then, instead of using one of the built-in routers, you would use the <Router> component.

// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'

ReactDOM.render((
  <Router history={history}>
    <App />
  </Router>
), holder)
// some-other-file.js
import history from './history'
history.push('/go-here')