Rasmus
Rasmus

Reputation: 4180

Handle data between two completely separate React components

I'm rebuilding and replacing parts of an older e-commerce systems product page with parts written in React. Instead of rewriting the whole thing I'm doing it component by component and later on in the project I'm going to connect it in a more conventional way. But for now it's just part by part.

I'm currently trying to figure out how to handle data between two components, a ProductList and a Cart. The two components live in entire different places on the product page. If I'm pressing Add to cart in the ProductList I want the Cart to be able to react to that event, as well as pressing Empty cart in the Cart to trigger a change in the ProductList.

The components won't be siblings.

Basic structure of the app:

The HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <div>
        <!-- Lots of other stuff, PHP etc... -->
        <div id="list"></div>
        <!-- Lots of other stuff, PHP etc... -->
    </div>
    <!-- Lots of other stuff, PHP etc... -->
    <div id="cart"></div>
    <script src="static/js/app.js"></script>
</body>
</html>

The Javascript components:

import React from "react";
import ReactDOM from "react-dom";

import List from "./components/List";
import Cart from "./components/Cart";

ReactDOM.render(
<List />,
document.getElementById('list')
);

ReactDOM.render(
    <Cart />,
    document.getElementById('cart')
);

Since neither are a child to a common ancestor, how would I go about handling component communication in a good way?

Upvotes: 0

Views: 90

Answers (1)

Pasha  Aksyonenko
Pasha Aksyonenko

Reputation: 86

One way is to use Redux library, https://redux.js.org/basics/usage-with-react it could have a reducer for the cart store, And List and Cart component should e wrapped with container components that would be connected with cart store.

Also, you could use context API that was added in react 16.3 version https://medium.freecodecamp.org/an-introduction-to-react-16-3-context-api-basics-53382372dc35

I would say solution with redux is more preferable for this issue.

Upvotes: 1

Related Questions