I am creating Dynamic input fields I am validating some required fields my validated output in the array I try to show error values in input I cause some errors. I tried an some match with an index array but i not working
codeSandbox :https://codesandbox.io/s/floral-bash-lrvkc?file=/src/App.js:0-2399
thanks for Help
import React, { useState } from "react";
import "./styles.css";
function App() {
const [inputList, setInputList] = useState([{ firstName: "", lastName: "" }]);
const [formError, setFormError] = useState([]);
const [isSubmit, setisSubmit] = useState(false);
// 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: "" }]);
};
const Submit = (e) => {
e.preventDefault();
const errorMsg = inputList.map((list, key) => {
let error = {};
if (!list.firstName) {
error.errorfirstName = "FirstName is required";
} else {
error.errorfirstName = "";
}
if (!list.lastName) {
error.errorlastName = "LastName is required";
} else {
error.errorlastName = "";
}
return error;
});
console.log(errorMsg);
setFormError(errorMsg);
};
return (
<div className="App">
{inputList.map((x, i) => {
return (
<div className="box">
<input
name="firstName"
placeholder="Enter First Name"
value={x.firstName}
onChange={(e) => handleInputChange(e, i)}
/>
<input
className="ml10"
name="lastName"
placeholder="Enter Last Name"
value={x.lastName}
onChange={(e) => handleInputChange(e, i)}
/>
<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 style={{ marginTop: 20 }}>{JSON.stringify(inputList)}</div>
</div>
);
}
export default App;