Skip to content Skip to sidebar Skip to footer

How To Add Multiple Form Input Results Into Array State In React

I'm am an all around new coder and trying to learn React by building a small app that calculates how much cash one has (an app my kids can use). I am dynamically creating 5 compone

Solution 1:

I was able to find the error easily by opening the javascript console (F12 or right click -> inspect).

The error was thrown because you did pass handleCashInput as a prop to CashItemsList

<CashItemsList key={bill.id} bill={bill} onChange={this.handleCashInput} />

Also using an array with reduce was not a good idea because if you delete an amount and re-enter it, the total will be wrong. I did the following to solve it:

  1. I use an object instead of an array { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

  2. I pass the bill id to handleCashInput to be able to change the amount this.props.onChange(this.props.bill.id, newBillSubTotal)

  3. I update the correct bill value in the object like this const cashTemp = this.state.billFinalTotal;cashTemp[id] = newBillFinalTotal;
  4. I calculated the total by adding every value of the object together const bt = this.props.billFinalTotal;const total = bt[1] + bt[2] + bt[3] + bt[4] + bt[5];

Here's my JSFiddle

Solution 2:

You had two issues in your fiddle.

First, you didn't pass an onChange prop to CashItemsList from Parent. So I changed:

<CashItemsListkey={bill.id}bill={bill} />

to:

<CashItemsListkey={bill.id}bill={bill}onChange={this.handleCashInput} />

The second issue is that the return of array.push() is not the full array, so in your "handleCashInput()" method on Parent, using array.concat() instead of array.push() solved that issue, by changing this:

const cashTemp = this.state.billFinalTotal.push(newBillFinalTotal)

to:

const cashTemp = this.state.billFinalTotal.concat(newBillFinalTotal)

Here's an updated fiddle that works: https://jsfiddle.net/ggtu71gh/1/

Note: it doesn't seem that you've implemented the subtotal functionality so this only attempts to fix the errors in what you've already implemented.

Post a Comment for "How To Add Multiple Form Input Results Into Array State In React"