Nicla Marino
Nicla Marino

Reputation: 97

Render multiple inputs React

I've created a simple Budget app using React. The user can add Income/Expense Description and Value by filling out the inputs and the final result gets added to the Expenses/Incomes lists.

I managed to add the Income/Expenses values (numbers): I've created a setState with incomes: [1, 3, 4], map around the income array and print out the values by updating the state.

I can't understand how to add the description. I've checked some questions here on Stack but they only use setState and creating a state for each element (incomes, incomeValues, expenses, expensesValue), which is not what I want.

Is there a way to do this without involving too many states? Maybe using an Object?

Github Link

Upvotes: 1

Views: 336

Answers (1)

Webber
Webber

Reputation: 5524

Your state is an object

{
  monthlyBudget: 0,
  incomesSum: 0,
  expensesSum: 0,
  incomes: [0],
  expenses: [0]
}

What you could do instead of adding more numbers to the incomes array is add objects to the incomes array. Exactly like you guessed.

{
  monthlyBudget: 0,
  incomesSum: 0,
  expensesSum: 0,
  incomes: [
    { amount: 0, description: 'some description' },
    { amount: 1, description: 'second description' },
  ]
  expenses: [0]
}

in which case you would still use map to access the properties of the object.

this.sate.incomes.map(income => {
  // do something with income.amount
  // do something with income.description
})

Upvotes: 3

Related Questions