Ask Question

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 />?

ReactJavaScriptmap

87 views

AuthorΒ΄s Anki Batsukh image

Anki Batsukh

Last edited on

1 Answer available

Best answer

I think the best solution is to spilt the logic. <RenderCards /> should only care about presenting the cards.

For calculating the total price you can write an extra function getTotalPrice() for example

const ResultPage = () => {
  const products: Product[] = [...];

  const RenderCards = () => {
    return products.map(product => <Card ... />);
  }

  const getTotalPrice = () => {
    let total = 0;

    products.forEach(product => { // of cource you can use `reduce()` here if you want πŸ˜‰
      total = total + (product.quantity * product.price);
    });

    return total;
  }

  return (
    <>
      <RenderCards />
      <Summary totalPrice={getTotalPrice()} /> // Tada!
    </>
  )
}
Last edited on