How to pass computed value out of a map function to next component in ReactJS?
I have an array of product that I render as a list. On the right side I want to show the total price of the products. For rendering the product list I am using a function which maps the products array and returns them as <Card />
components. Within the function I calculated the total price, but I don't know how to pass it to the next <Summary />
component.
interface Product {
id: number;
title: string;
quantity: number;
price: number;
}
const ResultPage = () => {
const products: Product[] = [...];
const RenderCards = () => {
let totalPrice = 0;
const cards = products.map(product => {
total = total + (product.quantity * product.price);
return (
<Card key={product.id} product={product} />
);
});
console.log('Total price:' + totalPrice); // RIGHT PRICE!
return cards;
}
return (
<>
<RenderCards />
<Summary totalPrice={0} /> // need to pass the price here...
</>
)
}
How can I pass the totalPrice
value that I calculated in <RenderCards />
to <Summary />
?
1456 views