Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist state across react router transitions

I've got the fairly typical react-router app set up:

var App = React.createClass({
    render: function() {
        return ( < RouteHandler /> );
    }
});

var routes = (
    <Route handler = { App }>
        < Route name = "Todo" path = "todo/:id" handler = {Todo}/>
        < DefaultRoute name = "Todos" handler = {Todos}/>
    </Route>
);

Router.run(routes, function(Handler) {
    React.render( < Handler /> , document.getElementById('content'));
});

My issue is that my Todos component has some search filters on it, and I want to persist those filters when I transition to a specific Todo and back. The obvious solution is to save those filter values on App's state, but I can't figure out an elegant way to allow Todos access to App's state.

Any hints?

Addendum: This app is using Reflux as well as react-router.

like image 567
Matt Welch Avatar asked Aug 20 '15 19:08

Matt Welch


People also ask

How do you preserve the state in react?

We can use localStorage and URL params to persist the App state in a React Application. For a simple use case, we can use URL params. If the data is a bit more complicated, we can go for storing it in the localStorage.

How do you pass a state from one route to another in react?

With react-router, you pass state or data from one component to another component to use the react-router Link component. Data pass more quickly in the new version of react-router (v6). For example, you can pass an object's data into one component to another component.

Does react router reset state?

If you change it manually then you basically reload the app completely which resets the state.

Where is react router state stored?

Short answer is that react-router uses the history module, which in turn uses the browser's history api. If supported, state is stored in memory by the browser's history api. If not supported, then the history module stores the state.


1 Answers

I would the url to save the state filters and page numbers for listings.

One of react routers "Benefits of this Approach" is: URLs are your first thought, not an after-thought.

The url is a foundational part of the web, use it to your advantage don't try to avoid it.

By saving the filter state in the url you get back button support for free and you allow your users to keep that filtered state as a bookmark or link.

like image 81
PetersenDidIt Avatar answered Oct 14 '22 01:10

PetersenDidIt