I am trying to update history in react
when the user navigates from one page/route to another. But confused about what method I should use to achieve this and why?
import { browserHistory } from 'react-router'
browserHistory.push('/bag')
OR
import { routerMiddleware, push } from 'react-router-redux'
const middleware = routerMiddleware(browserHistory)
const store = createStore(
reducers,
applyMiddleware(middleware)
)
store.dispatch(push('/bag'))
Please help. Thanks in advance :)
You can either push a new record onto the top of the history stack or you can replace the top record. If you use push , and then hit the browser's back button, it will take you back to the page you are currently on, but if you use replace it will take you two pages back.
React Router uses the history package, which builds on the browser history API to provide an interface to which we can use easily in React apps. location - (object) The current location. May have the following properties: pathname - (string) The path of the URL.
Both BrowserRouter and HashRouter components were introduced in React Router ver. 4 as subclasses of Router class. Simply, BrowserRouter syncs the UI with the current URL in your browser, This is done by the means of HTML-5 History API. On the other hand, HashRouter uses the Hash part of your URL to sync.
Essentially, if you understood the reason for you to use redux and react-router-redux :
store.dispatch(push('/bug'))
is keeping the navigation state in the store, pushes and navigates to the route
whilst
browserHistory.push('/bag')
just pushes and navigates to the route.
From the source code itself
/**
* These actions correspond to the history API.
* The associated routerMiddleware will capture these events before they get to
* your reducer and reissue them as the matching function on your history. */export const push = updateLocation('push')
Id suggest looking into the source code when trying to understand differences or how things work. Its good for learning and also for deeply understanding whats going on with the libraries you're using :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With