I have an dynamic created fields (input tag)
const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data
{navtive?.map((item, index) => {
return (
<input
type="text"
name={item.id}
onChange={(e) =>
handleChange("fee", e.target.value, index, item.id)
}
/>
...
{rolls?.map((item, index) => {
return (
<input
type="text"
name={item.id}
onChange={(e) =>
handleChange("fee", e.target.value, index, item.id)
}
/>
Expected Output:
const output = {
native: [{id: 1, fee: "12"}, {id: 5, fee: "2"}],
rolls: [{id: 4, fee: "1332"}],
};
onChange function :
const handleChange = (field, value, index) => {
setData((prevState) => {
const nextState = [...prevState];
nextState[index][field] = value;
return nextState;
});
};
How to get the expected output ? What am I making wrong in the onChange function.
Thank you
Hi I am Reproduced with one one example and I add some comment lines
codeSandBox :https://codesandbox.io/s/floral-bash-lrvkc?file=/src/App.js
import React, { useState } from "react";
import "./styles.css";
function App() {
const [inputList, setInputList] = useState([{ firstName: "", lastName: "" }]);
// handle input change
const handleInputChange = (e, index) => {
const { name, value } = e.target;
const list = [...inputList];
list[index][name] = value;
setInputList(list);
};
// handle click event of the Remove button
const handleRemoveClick = (index) => {
const list = [...inputList];
list.splice(index, 1);
setInputList(list);
};
// handle click event of the Add button
const handleAddClick = () => {
setInputList([...inputList, { firstName: "", lastName: "" }]);
};
// CHANGE HERE: a flag to be set when there is an error
const Submit = (e) => {
e.preventDefault();
console.log(inputList);
};
return (
<div className="App">
{inputList.map((x, i) => {
return (
<div className="box">
<div>
<input
name="firstName"
placeholder="Enter First Name"
value={x.firstName}
onChange={(e) => handleInputChange(e, i)}
/>
</div>
<div>
<input
className="ml10"
name="lastName"
placeholder="Enter Last Name"
value={x.lastName}
onChange={(e) => handleInputChange(e, i)}
/>
</div>
<div className="btn-box">
{inputList.length !== 1 && (
<button className="mr10" onClick={() => handleRemoveClick(i)}>
Remove
</button>
)}
{inputList.length - 1 === i && (
<button onClick={handleAddClick}>Add</button>
)}
</div>
</div>
);
})}
<button onClick={Submit}>Submit</button>
</div>
);
}
export default App;