Take a look at the react docs for Lifting state up.
Move your cart
state up into the closest common ancestor - App
.
From App
, pass cart
and setCart
as props into both Products
and Cart
as needed.
import React, { useState, Dispatch, SetStateAction } from "react";
import { render } from "react-dom";
interface IProduct {
id: number;
name: string;
price: number;
}
const App = () => {
const [cart, setCart] = useState<IProduct[]>([]);
return (
<div>
<Products cart={cart} setCart={setCart} />
<Cart cart={cart} />
</div>
);
};
function Cart({ cart = [] }: { cart: IProduct[] }) {
return (
<div>
<h2>Cart</h2>
{cart.map(item => (
<div>{`${item.name}: £${item.price}`}</div>
))}
</div>
);
}
function Products({
cart,
setCart
}: {
cart: IProduct[];
setCart: Dispatch<SetStateAction<IProduct[]>>;
}) {
const items: IProduct[] = [{id: 1,name: "Product One",price: 20},{id: 2,name: "Product Two",price: 56},{id: 3,name: "Product Three",price: 13}];
const handleClick = (
e: React.MouseEvent<HTMLInputElement, MouseEvent>,
item: IProduct
) => {
e.preventDefault();
setCart([...cart, item]);
};
return (
<div>
<div>
<h2>Products</h2>
{items.map(item => (
<div>
{`${item.name}: £${item.price}`}
<input
type="submit"
value="+"
onClick={e => setCart([...cart, item])}
/>
</div>
))}
</div>
</div>
);
}
render(<App />, document.getElementById("root"));
Stackblitz