Share Info betwen brothers components - reactjs

I have to find a solution to share information between components in React js.
The use case is that in an online store when a guest tries to add a product to his wishlist he should be redirected to the registration page and after registering it should be automatically added to his wishlist.
I tried with window.localStorage and made it work but I was told that it was not necessary to do it this way, the page is a bit complicated and the components do not have common ancestors the component tree is like this.
<App>
<Routes>
<SearchPage>
<Gallery>
<GalleryItem>
<AddToListButton>
</AddToListButton>
</GalleryItem>
</Gallery>
</SearchPage>
</Routes>
</App>
<App>
<Routes>
<Signin>
</Signin>
</Routes>
</App>
<App>
<Routes>
<Route>
<WishlistPage>
<Wishlist>
</Wishlist>
</WishlistPage>
</Route>
</Routes>
</App>
and I have to pass the button information to the registration page and then make it redirect to its wish list when it registers, apart from useContext what other method could I use?

It depend on the requirements, using localStorage allows you to store user session between tabs, even between sessions.
sessionStorage works similar but it stores data only within single session (for example - one browser tab).
You can try to use React Context API (as you mentioned).
One more is to use centralized store (for example React Redux).
Of course there are some additional browser features like IndexedDb or websql to persist some data for the user, but their support for various browsers can be different.

You have plenty of options, starting with the ones you have out of the box.
Lift the state up The best solution for non complex use cases is to get the state to the parent component and pass down the state value and a function that modifies the state to this sibling components that you want talking to each other.
Context If you have a piece of state that lots of children components are depending on you can create a context, wrap the parent component in a context provider and consume that in the childrens with useContext.
Or you can find libraries for state management here
If this "add to wishlist" action is something that happens in the server I highly recommend react-query. If not, try zustand it's easier to use than redux and feels very similar to context but with less boilerplate and without the need to wrap things in a context provider

Related

How to render a page to base url in react

I need to render a page for base url in react. I defined base url as,
<Router basename="/baseUrl">
<Switch>
<Route path={"/childUrl"}
</Switch>
</Router>
I am able to render page via /baseUrl/childUrl. When accessing, /baseUrl it redirects to /baseUrl/childUrl. How can I set a different page to /baseUrl
I know this is old, but in case anyone else stumbles upon this I would recommend using redux-first-router. It lets you dispatch actions either by changing the url in your browser, or the regular react way. This lets you control how components are rendered and keep the state of your application in sync with the url, without having multiple sources of truth.
Michael Sargent did a brilliant explanation, which can be found here.
And of course, you can also check out the git repo.

React Router: retaining state of previously visited "route"s

I have a React application (that uses React Router) with five "routes"/sub-pages.
If the user enters information on a sub-page (e.g. checks a checkbox/enters text in an input field on the page), then visits another sub-page, and goes back to the previous sub-page, I want that sub-page to have retained the state the user left it in.
I also need to be able to retrieve the state of all sub-pages, at some point.
Is this possible/viable using React Router, or is there a better way to do it?
If you didn't want to use Redux or similar to maintain data between route changes, you could always have a wrapping component that sits above <Router> and passes data down to each relevant <Route> via react-routers render prop solution. You would need to provide callbacks for each update that a sub-section might need to make however, which isn't necessarily scalable.
Alternatively, another method is to take the state of the sub-section away from the component and into the URL via parameters, for example search filters that you might commonly see in URLs. However this isn't always desirable.
Implementing Redux would be a far better solution to the problem though.

Structuring a modular enterprise application with React?

A lot of us will be familiar with the enterprise web applications that are the be all and end all of the business data. They are usually a collection of various modules behind a login authentication and role based authorization. Instead of the user login in to various smaller application they login once and have a dashboard/menu of what they have access to.
The user login
Their roles are retrieved and stored in session
Application load with a large menu populated according to their roles (CRM, CMS, no admin panel, etc.)
We have been thinking of how we could leverage some of the newer frameworks out there (Angular, React, Vue) or if we should at all for these kind of applications.
I am a struggling when it come to state management. I understand the idea of managing the state using something like Redux with React for smaller components but if various part of a larger application are completely unrelated to each other I am left wondering how complex and how large this state might get to be?
Using React as an example my root component after login might be (I am not sure as I am not extremely familiar with React yet).
const Root = () => {
return (
<div className="container">
<Router history={browserHistory}>
<Route path="/" component={dashboard}/>
<Route path="/crm" component={crm}/>
<Route path="/cms" component={cms}/>
<Route path="/module1" component={module1}/>
...
<Route path="/moduleN" component={moduleN}/>
</Router>
</div>
)
}
ReactDOM.render(<Root />, document.getElementById('root'));
Is this the better approach even if the multiple routes have nothing in common (the cms doesn't care about the crm) that they should all share the state or would actually reloading the page and going to different smaller more focused single page applications be preferred?
For example, using traditional server side logic to present the menu going to different html file for each modules.
What you are referring to is called lazy loading, that will break down your routes in different JS files and only load them on requests. You can refer to this link on how to use lazy loading in vue.js
https://router.vuejs.org/en/advanced/lazy-loading.html
Here is a way in React (does not seem to be native, correct me if I am wrong)
Dynamic loading of react components

What is routing? Why is "routing" needed in single page web apps?

I understood that routing libraries for SPAs like https://github.com/ReactTraining/react-router help to parse the URL and put the app into a corresponding state of a state machine.
Is there more to routing than this?
Why is routing needed in the first place?
Why are URLs important? For example in a desktop app there are no URLs, so what's the big deal about them in a web app?
I also have this problem: "Why do we need routing?". You can write apps without routing at all. The code can get messy but still, it is not impossible.
My biggest reason for having routing is because if the user hits the Back button of the browser (Forward button as well, for that matter), he will not be navigating within the app. The user might expect to navigate within the app using the history of the different "pages" he loaded previously. Instead, he will be thrown out of the web app. Hitting the Refresh button would also throw him to the root of the app.
From the user's point of view, it is a regular web app (he doesn't need to know how it is designed: SPA or otherwise) and it should work as any web app/website should work. Routing ensures this, doesn't it?
This is a very good question, and one that I don't see discussed as often as I think it should be. The short answer is that often, in a Single Page Web Application, you don't need routing. If you are building an application which doesn't require its pages to be indexed by Google, and you either don't care, or don't want the user to be able to Bookmark pages, then there is no reason to implement routing.
In an SPA, routing adds additional complexity and effort, so if you can avoid doing it, you should. Of course, modern frameworks such as Angular and React provide facilities for making routing much easier, but even then some things can be hard to do with routing, for example animating between pages.
A good example of a web application where routing would be redundant would be a multi-page form which you want to control the user's passage through and possibly prevent them from returning to pages which have became inapplicable.
Implementing such a form with routes would be a nightmare as you would have to prevent the user from visiting certain pages in their history.
It's useful to ask yourself what a route actually is in a SPA. It's easy to think of it as just a 'web-page', but what it really is is a state, and when you navigate between routes what you are really doing is navigating between different states of the app. The fact that the appearance of the app may change between states is incidental to what is really going on. So what a route does is give the user a means of returning to particular states of the app.
You should only implement a route in an SPA when there is a state of the app which you want the user to be able to return to.
An alternative, and perhaps more useful way of doing this, would be to implement Undo and Redo mechanisms.
Of course, even when you don't have routes you still have to care about what happens when the user clicks the History Back button, but then you simply have a modal alert which warns them that they are about to leave the app should they proceed with the navigation.
In desktop applications you have buttons and other controls to get what you want. So routing in UI apps would be the set of all UI controls.
In web apps on the other hand, all functionality is accessed via some text which is the links and the parameters.
A URL is the path to access a functionality. Routing is like the mechanism to decide which functionality to call based on the provided URL and params.
So basically routing is a mapping between an URL and the functionality of a web server.
Routing in SPAs is used to load certain parts of the web app e.g. yourappurl.com/profile/userid/ will load the profile part of an SPA with the right user profile corresponding to the userid. This can be seen in the GitHub example you provided:
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="about" component={About}/>
<Route path="users" component={Users}>
<Route path="/user/:userId" component={User}/>
</Route>
<Route path="*" component={NoMatch}/>
</Route>
SPA refers to the fact that in general you have an index.html as your "main view" and then depending on the routing you add/remove certain parts from the index.html with frameworks like React or AngularJS etc.
I have the same question from time to time.
I would like to say router in SPA is a component hierarchy helper.
As #tech4242 pointed out, we don't have an something like segue in iOS. So what should we use to help users navigate if we don't use router? We are talking about SPA here. So we can manage this in store or state. Yes, that's feasible but not preferable.
Try to think this from the perspective of using a component-oriented library (either React or Vue). Using router help us use a certain component for a specific route. When users move back and forth between different route, we are relying on the route to tell what component to display. We simply couple a component with a specific route, which makes our root component (normally called App) clear, maintainable and readable. Without router, either the root component or state would be messy and hard to maintain.

Remounting all react child components after root state change

I'm building a pretty large application and would like to get some insight on the best way to re-render the application based on a root component state change.
Sample Architecture
<Route path="/" component={App}>
<Route component={Layout}>
<IndexRoute component={Page} />
<Route path={page} component={Page}></Route>
...
</Route>
<Route component={Layout}>
<IndexRoute component={Page} />
<Route path={page} component={Page}></Route>
...
</Route>
In my architecture after a successful login i'm storing the users data in my App component. Every user has a client key which is used as the identifier as to which clients database/data to display. The behavior i would like to accomplish would be to update my current page with the new clients data after the a client change.
Now i could pass my data down to my components as props from my App component but i think this would be inefficient because of two reasons.
I would have to get the data for all my routes before rendering my App component.
My data would become "stale" until i re-render my App component.
Because of these reason i decided to let each page fetch it's own data using the componentWillMount life cycle hook, and passing the data down as props to the pages child components. This works for me because i'm able to fetch fresh data for each page upon navigation.
What i'm currently experiencing is that after a client change my application re-renders but since my current page has already mounted it doesn't fetch the new client data. But everything works as expected if i navigate away from the current page and then back to the page.
One solution i have in mind is to pass the users data down to each page and use the componentWillReceiveProps life cycle hook and perform a comparison check in order to fetch new data. I would like to prevent that if at all possible since my application will have 40+ pages.
Any suggestions would be greatly appreciated.
What you have mentioned about
pass the users data down to each page and use the
componentWillReceiveProps life cycle hook and perform a comparison
check in order to fetch new data.
is perfectly fine. Few examples of such a pattern in the wild:
Redux repository real world example
React Router core team recommends this method too as per issue here.

Resources