reactjsmultiple-input

How save state of multiple input in react


I am learning React. I have created a sandbox for you.
In the sandbox, You will see multiple inputs for entering name,credit, debit.
Currently, If I type on name input, it will update all name inputs similarly for credit and debit inputs.

What I want :
Whenever we click on SAVE button, I want to get data as :

credits: [
  {
    amount: 10,
    index: 0,
  },
  {
    amount: 12,
    index: 1,
  },
],
debits: [
  {
    amount: 5,
    index: 0,
  },
  {
    amount: 2,
    index: 1,
  },
],
};

NOTE : In the sandbox, you will see I have defined an array, const arr = [0, 1]. So according to the length of the array, the number of inputs will increase.

Please help me. I am stuck here !


Solution

  • Can you create state as array?

      const [data, setData] = useState(Array(5).fill(null).map(() => ({
        name: "",
        credit: "",
        debit: ""
      })));
    

    And later update only needed item from this array?