Reputation: 4701
What is the difference between hashHistory
and context.router
? Both of them route url and seem to work the same.
Upvotes: 0
Views: 123
Reputation: 36787
hashHistory
is an instance of a history
object created by the history module. It works by modifying the hash of a URL.
In React Router, a <Router>
must be passed a history
object. You can create and configure your own object, but for convenience, they also create hashHistory
and browserHistory
objects for you. Those objects can be imported and used anywhere throughout your project, including within your components. The downside to using them is that you cannot configure them yourself. If you need to use any of the history configuration options, then you will need to create your own history
object.
import { hashHistory, Router } from 'react-router'
render((
<Router history={hashHistory}>...</Router>
), holder)
// or
import { Router } from 'react-router'
import { createHashHistory } from 'history'
const history = createHashHistory({ /* configuration options */ })
render((
<Router history={history}>...</Router>
), holder)
Within the components rendered by the <Router>
, you can access the context.router
object. That includes a number of methods from your history
object. Caling those methods is the same as importing hashHistory
within that file and calling whatever navigation function that you need.
const MyComponent = (props, context) => (
<div onClick={() => { context.router.push('/other-page') }}>Click Me!</div>
)
const MyComponent = (props) => (
<div onClick={() => { hashHistory.push('/other-page') }}>Click Me!</div>
)
The downside of this is that your components are less portable. Whereas using context.router
will use whatever history
object you passed to the <Router>
, you would need to modify the component if you decided to switch from hashHistory
to browserHistory
.
Upvotes: 1