-3

I'm creating a POS system with ReactJS. Should I use a for loop to calculate the total amount? Is there any other way to do this?

let product = testProducts;
let subtotalEl = document.getElementsByClassName("Subtotal");
let quantity = document.getElementsByClassName("Quantity");
for (var i = 0; i < product.length; i++) {
  subtotalEl[i].innerHTML = product[i].UnitPrice * quantity[i].value;
}
delfincortesb
  • 85
  • 1
  • 6
  • 3
    There's never a good reason to use `getElementsByClassName` in React (nor `.innerHTML` nor `.value`) – CertainPerformance May 12 '22 at 04:08
  • If you're talking about summing line items: the rendering should be using an (array, object, ...) of line items w/ each item having data (description, quantity, price, ...) and the total should be calculated using that data--not anything in the view layer. – Dave Newton May 12 '22 at 04:10
  • In your code example, you have made use of absolutely *nothing* that React has to offer. Maybe look at some of the answers to [Loop inside React JSX](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx) – Wyck May 12 '22 at 04:13
  • Unfortunately, as others have already pointed out, you are using React incorrectly. [Here is a comment I wrote for a similar antipattern explaining what the problem is](https://stackoverflow.com/questions/71732114/hi-all-am-creating-responsive-navbar-in-react-when-i-clicked-on-toggle-button-i#comment126768178_71732114). – Alexander Nied May 12 '22 at 04:21

1 Answers1

0
  1. You are not using react js, your code looks like JavaScript.
  2. Yes, you can use a loop to add, but in React it is recommended to use map for iterations.

For example:

const sum = array_object
  .map((item) => item.quantity)
  .reduce((prev, curr) => prev + curr, 1);

As you can see, map was used to go through the array, and reduce to add the values.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • (As a side note, `map` is for transforming lists, not generic iteration, and it's not strictly ReactJS-related.) – Dave Newton May 12 '22 at 15:00