Pass data from child to parent when navigating back with react router? - reactjs

I know I can pass data when navigating forward with Link, Route ..
<Route
path="/release"
exact
render={() => <ManagedEventsList pages={this.state.pages} />}
/>
witten here: https://tylermcginnis.com/react-router-pass-props-to-components/
but is it possible to pass data also when browser back button was pressed?
This article show how to pass from state from child to parent without react router. Would it work with react router?
https://dev.to/zeyadetman/how-to-pass-state-between-components-in-reactjs-2pg1

With react-router-dom, no, it isn't possible to pass state with a back navigation. The history object can only send state with push or replace actions. The go actions only update the pointer to the current location in the history stack, i.e. go(-1) is equivalent to goBack().
If you need to preserve data correlated to the history stack or if you need to also "send" data during a back navigation then you'll need a library outside of react-router-dom. Redux would be a decent option, if you are already using it, to save in state either data used during navigation, or to along with doing a history.goBack() to also dispatch an action to save some "goBack" data in state to be retrieved via check on the previous page. Others like Redux Sagas or Thunks allow you to issue side-effects along with updating state. With these you could create your own goBackWithState action that saves some state in your Redux state and then issues the back navigation.
react-router-dom history

Related

React Router Dom History goBack injecting state

Is there a way to use the history hook function goBack(), in the same way, we use the Link component?
<Link to={{pathname:'/brand', state: {id}} />
Let's say I want the user to be able to go back to a previous page with an indexed table, to a precise table page. so I will first pass the index value in the Link state component, then on the way back using goBack() is there a way to pass again the state in order to redirect to that specific index?
hope it's clearer now

React Router: Selective route props passing to children

Consider the following example:
return (
<Router>
<Route component={Table} path='/table' />
</Router>
);
Let's assume we're on the /table route the entire time.
Whenever the URL changes, the Router will re-render one of the Route components (even when the path doesn't change, see: https://github.com/ReactTraining/react-router/issues/7539).
My users like to share the URLs with each other and expect the displayed page to be more or less the same. Therefore, I need to store some information into the URL, e.g. /table?country=Narnia. The problem is, when I append or edit the search query, the child component will be re-rendered (because the search inside props.location changed), which will in turn trigger the update of its children and so on. In truth, only a part of the page needs to take into account this change inside the URL, e.g. table might apply some sort of filtering logic to the data.
What is the best way to achieve this behavior? I am talking about the likes of useSelector in Redux or Context Provider Pattern with React's Context.
Using useLocation/useMatch in nested children will also result in unwanted renders - one component might be interested in changes to parameter country, but some other might want subscribe to parameter age. useLocation would cause both to re-render when the url changes.
I am trying to avoid writing custom useEffect to control rendering of components subscribing to route changes.

Permanent States in React - React-Router

I have a problem: I have a NavBar that loads an AJAX which retrieves a name and another data. Well, the problem is that this data stores them in states of the declared component itself as NavBar.jsx and when I use routes (react-router) the component is mounted and dismantled losing its states, therefore, every time that change of route has That re-make the AJAX call. This same problem I have for a button 'Enter', which has status 1 and when someone is logged in takes 0 status, but every time I change the route returns to state 1 (as if it were not logged, although it is actually logged). My question is: How can I create states that are maintained despite changing routes? (I know this is not possible, with states I am referring to variables, or anything I can declare that does not change value every time you reassemble the components, in this case NavBar, when changing paths. Thank you.
This can be solved in several ways.
save the returned data in localStorage, check in localStorage before doing the ajax call, is the data exists, just use it instead.
Use redux - this moves the state to the app level instead of the component, unmounting the component will not delete the state.
do not re-render the navbar on each navigation(if it's possible in your app).
See the tutorial for nested routes for react-router ;
https://github.com/reactjs/react-router-tutorial/tree/master/lessons/04-nested-routes
this option means that route changes will only re-render the "internal page" and not constant things like the navbar, submenu, footer etc.

react-router-redux push, state change reset

I have an application that creates a new record and redirect the history to the new record page using react-redux-router push. This redirection is made by a "smart component" inside another smart component.
The state of these components is stored on a redux store.
After redirection if I go back to the previous page it's state is dirty.
Is there a way to reset the state ? Or should I manually clean it up before the redirection.
Currently I'm listening on the reducer for LOCATION_CHANGE and resetting it but this seems manual and hacky.
Shouldn't the component unmount when it's route is not rendered anymore?
I'm unclear from your question - is the state that you're wanting to be reset stored within that component (setState) or within the Redux store?
If it's within that component, and the component is unmounted, then its state should be automatically reset.
If it's within the Redux store, then the whole point of the Redux store is that it exists persistently, outside of whatever components are mounted. One common way of resetting state in that case would be to dispatch a clear or reset action within the component's componentWillMount (i.e., the component ensures that it always starts with a good state).

Is there a clean way to conditionally load and render different components for the same React Router route?

The use case is that I want to map the root (/) to one of two different components based on whether the user is logged in or not, and I want these two components to reside in different bundles and lazily loaded, so simply putting the login check in the render() method would not do.
I tried to use dynamic route definition with require.ensure() to lazily load the component, and it works for the first time, but after changing the login state the component doesn't get updated (even if I navigate to another route and back to / ).
I tried to force re-rendering the router by setting props on the component that contains the router, both manually and by making it a Redux connected component, and I also tried to add a listener to the Redux store and change the component state in response to login change, but in all of the attempts I got the error "You cannot change ; it will be ignored" and the component doesn't change.
My ugly solution is to have the different component loading code outside of the router, listen to the login state change and in response load the matching component and set it in the wrapping component's state, which is referenced in the render() code. Is there a clean "React-Router-ish" way to do what I want?
React Router 4 pretty much solves this as it made the route configuration part of the component rendering, so having conditional rendering is the same whether it's based on the location or on other props/state.
The closest thing to a clean "React-Router-ish" way to do that is to use the React Router Enterhooks.
An enter hook is a user-defined function that is called when a route is about to be rendered. It receives the next router state as its first argument. The replace function may be used to trigger a transition to a different URL.
So, use the onEnter(nextState, replace, callback?) attribute on your <Route />.
Called when a route is about to be entered. It provides the next router state and a function to redirect to another path. this will be the route instance that triggered the hook.
If callback is listed as a 3rd argument, this hook will run asynchronously, and the transition will block until callback is called.
The general best practice I follow is to place the auth-check flow away from your routes, and place it inside the transition events/hooks.
The usual behavior is - before the route handler actually gets rendered, check the auth, and redirect the user to another route. In your case, if you want to use the same route, but render different components - you should be able to do that using the same technique too. However, that's not a common thing (based on what I've seen), but it should be possible.
For a complete example of this approach, here's the auth-flow code example you can check. It is shared by the creators of React Router, so it looks credible to me.
PS: My answer is valid for React Router versions > 0.13.x.

Resources