Ad

React Router Persist Route History On Page Reload

Is there any way I could persist react route history on page reload and pass it to my component. Ex:- I am on a dashboard component with link "/" then I go to another component using link "/ab" then I go to another component using Link "/bcd".

Flow = "/"->"/ab"->"/bcd"

Now when I reload the page when I am on "/bcd" the router is not persisting the older routes. So as a result I can't return to the previous components/pages. How could I return to previous components even after page reload?

I am using HashRouter. and React-router version is 4.3.0

Ad

Answer

Yes, @babs' solution will utilize the browser's back capability to simply go back a page, but I had a similar requirement to your issue where I needed to track where a user came from in the app, persisting through page reloads/refreshes. We're using redux and have a history listener on the router that dispatches a "LOCATION_CHANGE" for every navigation.

The problem was it only gives you part of the story and is fired after the route changes, so seeing where the route was from was a no-go. I created a history reducer that simply stores in state a queue/stack of the last N changes paired with a set of selectors that expose to the app the current (top) and previous (top - 1) location/history objects. This is because while react-router's history is mutable it doesn't provide all what you expect*.

The basic pattern to listen for changes is:

// Listen for changes to the current location.
const unlisten = history.listen((location, action) => {
  // location is an object like window.location
  console.log(action, location.pathname, location.state);
});

If you're not using a state management like Redux you can still use this callback to store a history of sorts in your route component, or root app component where you create the router history object. Pass as props to children or use the new context system, or upgrade and use redux, to get your history.

* MemoryHistory does actually provide a history stack that you can access

Ad
source: stackoverflow.com
Ad