Similiary to accepted answer what you could do is use react
and react-router
itself to provide you history
object which you can scope in a file and then export.
history.js
import React from 'react';
import { withRouter } from 'react-router';
// variable which will point to react-router history
let globalHistory = null;
// component which we will mount on top of the app
class Spy extends React.Component {
constructor(props) {
super(props)
globalHistory = props.history;
}
componentDidUpdate() {
globalHistory = this.props.history;
}
render(){
return null;
}
}
export const GlobalHistory = withRouter(Spy);
// export react-router history
export default function getHistory() {
return globalHistory;
}
You later then import Component and mount to initialize history variable:
import { BrowserRouter } from 'react-router-dom';
import { GlobalHistory } from './history';
function render() {
ReactDOM.render(
<BrowserRouter>
<div>
<GlobalHistory />
//.....
</div>
</BrowserRouter>
document.getElementById('app'),
);
}
And then you can just import in your app when it has been mounted:
import getHistory from './history';
export const goToPage = () => (dispatch) => {
dispatch({ type: GO_TO_SUCCESS_PAGE });
getHistory().push('/success'); // at this point component probably has been mounted and we can safely get `history`
};
I even made and npm package that does just that.