score:0

Accepted answer

to answer how to loop through an array, you can use a simple for loop in javascript as you would in a language like c;

let total = 0;
for(let i = 0; i < items.length; i++) {
    total += item[i].price
}

react following a functional approach, we prefer map and reduce as it makes your code more declarative. hence,

const total = items.reduce((acc, item) => {
  return acc + item.price;
}, 0)

your code would look like this then,

import react, { component } from 'react';
import logo from './logo.svg';
import './app.css';


export class cart extends component {
  constructor(props) {
    super(props);
    this.state = {items: props.cart,cart: [],total: 0};
  }


  counttotal() {
    return this.state.items.reduce((acc, item) => {
      return acc + item.price;
    }, 0)
  }

  render() {
    return(
      <div classname= "webcart" id="webcart">
        { this.counttotal() }
      </div>
    );
  }
}

class app extends component {
  render() {
    return (
      <cart cart={
              [
                {
                  item:"hoodie",
                  price:25,
                  size:"large"
                },
                {
                  item:"gloves",
                  price: 12,
                  size:"large"
                },
                {
                  item:"boots",
                  price:30,
                  size:"large"
                },
              ]
            } />
    );
  }
}

export default app;

note there is not setstate used. total is derived data. derived data must not reside in state.

yet if for some reason you still need it, counttotal would look like this,

counttotal() {
   this.setstate(state => {
     return {
        total: state.items.reduce((acc, item) => {
          return acc + item.price;
        }, 0)
     };
   });
}

score:3

you should not assign directly to state, you should use setstate instead. foreach is fine, but i would recommend you skip foreach and map and use reduce, pulling only the price key out of the object:

counttotal() {
   this.setstate({
      total: this.state.cart.reduce((total, { price }) => total + price, 0)
   });
}

Related Query

More Query from same tag