I have e-commerce based page. The entire page is not wrapped within a single react app.
The bulk of the page's static content is rendered on the server-side using EJS. Upon rendering on the client we initialize two isolated react apps with their own states.
Each product item has an Add to Cart button. When the user clicks on it we need to immediately update the count in the cart without refreshing the page.
Now the question I have is if there is a way to achieve this without rendering the entire page in react. Below is the rough HTML markup I have.
<navbar>
<navbar-links/>
<div id="site-cart-app"></div> // this is where the cart react app is initialized.
</navbar>
<div id="product-list-app"></div> // this is where the product list app is initialized.
High-level summary - To make sync multiple React app on a single page you need a common data source, like REDUX
(I personally recommend) and subscribe
to the REDUX Store
in multiple React app and update component accordingly.
How to achieve? (What I did with my project)
This seems simple but ain't.
The problem which I faced during implementation.
How to separate React projects with common Redux Store and reducers. - For this, I used Redux-Dynamic-Modules library which allows us to make a separate store or load reducers on a load of a component.
I'm still working on it but for your ref. Here is my git repo for a similar problem.
One of them, you add a service where you write the code request for Add or Remove card item and use Rxjs Subject and Subscribe from card component example here.
In your Services.js
import { Observable, Subject } from "rxjs";
export class CardService {
public static observable = new Subject();
}
In your productpage
import { CardService } from ./services/CardService";
//trigger when click to add or remove Card item
TollAdminService.observable.next({ cardItem, action });
And in your card component
import { CardService } from ./services/CardService";
// inside the component constructor like this
constructor(props) {
TollAdminService.observable.subscribe((cardItem: any, action: any) => {
//add your action code here...
}
}
Thanks
you can use common redux store to maintain the cart count, both Apps will use that store
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.