'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 1:[1]
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>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhishek kamal |
