As @Yoskutik
gave me a hint. So I used that hint to solve my problem and I got my final solution :
import React, { useState, useEffect } from "react";
import "./styles.css";
//constants
const arr = [0, 1,2]; // may contain n elements
export default function App() {
//states
const [data, setData] = useState({
credits: [
...Array(arr.length)
.fill(null)
.map((item) => ({
index: "",
name: "",
amount: ""
}))
],
debits: [
...Array(arr.length)
.fill(null)
.map((item) => ({
index: "",
name: "",
amount: ""
}))
]
});
//functions
const nameChangeHandler = (e, index) => {
const oldData = { ...data };
// oldData[index] = [...oldData, ]
if (e.target.name === "credit") {
oldData["credits"][index] = {
...oldData["credits"][index],
amount: e.target.value,
index
};
}
if (e.target.name === "debit") {
oldData["debits"][index] = {
...oldData["debits"][index],
amount: e.target.value,
index
};
}
// setData((prevState) => ({
// ...prevState,
// [e.target.name]: e.target.value
// }));
};
const formSubmitHandler = (e) => {
e.preventDefault();
//logging
console.log(data);
};
return (
<div className="App">
<h2>Multiple input form</h2>
<form onSubmit={formSubmitHandler}>
<table>
<tr>
<th>Sr. no.</th>
<th>Name</th>
<th>Credit</th>
<th>Debit</th>
</tr>
{/* mapping for muliple input */}
{arr.map((item, index) => (
<tr key={index}>
<td>{index}</td>
<td>
<input
type="text"
name="name"
value={data.name}
onChange={(e) => nameChangeHandler(e, index)}
/>
</td>
<td>
<input
type="number"
name="credit"
value={data.credit}
onChange={(e) => nameChangeHandler(e, index)}
className="amount"
/>
</td>
<td>
<input
type="number"
name="debit"
value={data.debit}
onChange={(e) => nameChangeHandler(e, index)}
className="amount"
/>
</td>
</tr>
))}
</table>
<div className="center mt-10">
<button className=" btn cursor-pointer">SAVE</button>
</div>
</form>
</div>
);
}