Sometimes, we want to get the browser history
object with React Router.
In this article, we’ll look at how to get the browser history
object with React Router.
Get History on react-router
We can get the history with React Royer by calling the createBrowserHistory
method.
For instance, we can write:
import { Router } from 'react-router-dom'
import { createBrowserHistory } from 'history'
import App from './App'
const history = createBrowserHistory({
//...
});
ReactDOM.render((
<Router history={history}>
<App />
</Router>
), holder)
We can also use the withRouter
higher-order component to inject the history object into a component.
For instance, we can write:
import { withRouter } from 'react-router-dom';
class App extends React.Component {
render () {
this.props.history;
}
}
withRouter(App);
We called withRouter
with App
to inject the history
prop to it.
Then in our App
component, we can get the history with this.props.history
.
Conclusion
We can get the history with React Royer by calling the createBrowserHistory
method.