How to get history on react-router v4?
This works! https://reacttraining.com/react-router/web/api/withRouter
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
render () {
this.props.history;
}
}
withRouter(MyComponent);
Basing on this answer if you need history object only in order to navigate to other component:
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
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')
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.