Neff
Neff

Reputation: 189

How map with function and text ReactJs

I would like to explain my problem of the day.

currently i map, everything works correctly

my problem and that I wish I could create a div in it in order to display the result of total , unfortunately I can't

Do you have an idea of how to fix this?

 {this.props.items.map(item => { 
 const product = this.props.items;
 let total = 0;

 console.log(total)
 console.log('yolo',product)
 console.log('yolo array',product[0].quantity)

for (let i = 0 ; i<product.length;i++){
console.log('products',product[i].quantity) 
total = total + product[i].quantity;                        
}
} 
)}

Upvotes: 0

Views: 37

Answers (1)

Francesco Di Stefano
Francesco Di Stefano

Reputation: 121

even if you were to render something using total, with this method you would render a "total item" for each item in props.items. What you want to use here is the reduce method. Here is an example with a very basic div, but you can decide what to render in place of it

<div>
{this.props.items.reduce((total,item) => item.quantity + total, 0)}
</div>

What the reduce methos does is returning a single value from a list of elements. The second parameter is your initial value, while he first is the callback that will be executed at each iteration

Upvotes: 1

Related Questions