I have two react components one is Cart and the other is CartItem, Inside Cart I am looping using .map the CartItem. Inside CartItem I have a line total which is price * item.count. How can I sum up all the line totals regardless how many CartItems I have, and return the Total so that I can have the overall value of the cart.
I tried to add a handle total function but its only returning line total of one element not all of them.
Here is the CartItem:
const CartItem = ({item, handleTotal}) => {
var [itemCount, SetItemCount] = useState(1);
var [Linetotal, SetLineTotal] = useState(item.price);
const incrementcount = () => {
SetItemCount(++itemCount);
};
const decrementcount = () => {
SetItemCount(--itemCount);
};
useEffect(() => {
handleTotal(item.id,Linetotal)
},[])
return (
<div>
<Product>
<ProductDetail>
<Image src={item.image} />
<Details>
<ProductName>
<b>Product:</b> {item.name}
</ProductName>
<ProductId>
<b>ID:</b> {item.id}
</ProductId>
<ProductColor color={item.color} />
<ProductSize>
<b>Size:</b> {item.size}
</ProductSize>
</Details>
</ProductDetail>
<PriceDetail>
<ProductAmountContainer>
<Add onClick={() => {incrementcount(); SetLineTotal(item.price*itemCount)}} />
<ProductAmount>{itemCount}</ProductAmount>
<Remove onClick={() => {decrementcount(); SetLineTotal(item.price*itemCount)}} />
</ProductAmountContainer>
<ProductPrice>$ {item.price*itemCount}</ProductPrice>
</PriceDetail>
</Product>
</div>
);
};
export default CartItem;
and Here is the Cart:
const Cart = () => {
var [total, setTotal] = useState([]);
const handleTotal = (id,price) => {
setTotal(id,price);
};
return (
<Container>
<Navbar />
<Announcement />
<Wrapper>
<Title>YOUR BAG</Title>
<Top>
<TopButton>CONTINUE SHOPPING</TopButton>
<TopTexts>
<TopText>Shopping Bag(2)</TopText>
<TopText>Your Wishlist (0)</TopText>
</TopTexts>
<TopButton type="filled">CHECKOUT NOW</TopButton>
</Top>
<Bottom>
<Info>
{IntheCart.map((item) => (
<CartItem key={item.id} item={item} handleTotal={handleTotal} />
))}
<Hr />
</Info>
<Summary>
<SummaryTitle>ORDER SUMMARY</SummaryTitle>
<SummaryItem>
<SummaryItemText>Subtotal</SummaryItemText>
<SummaryItemPrice>$ 80</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Estimated Shipping</SummaryItemText>
<SummaryItemPrice>$ 5.90</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Shipping Discount</SummaryItemText>
<SummaryItemPrice>$ -5.90</SummaryItemPrice>
</SummaryItem>
<SummaryItem type="total">
<SummaryItemText>Total</SummaryItemText>
<SummaryItemPrice>$ 80</SummaryItemPrice>
</SummaryItem>
<Button>CHECKOUT NOW</Button>
</Summary>
</Bottom>
</Wrapper>
<Footer />
</Container>
);
};
export default Cart;
2
Answers
You can create
updateTotal
function in theCard
component and once youincrese
ordecrement
item in theCardItem
update thetotal
value.updateTotal
function.Add the updateTotal function to
CardItem
If you need sub sum to so sub total, you can do like this.