You're using a single Boolean state inputError to decide errors for both the name and email field so that's why you see the error. There is no way to distinguish from which field the error occured.
Instead of that you can have a dedicated inputError object which acts as a Hashmap/Dictionary for your input fields with true/false indicating whether a particular field has error.
Whole code for reference :-
import { Grid, TextField } from "@material-ui/core";
import { useState } from "react";
import "./styles.css";
export default function App() {
const [inputError, setInputError] = useState({ name: false, email: false });
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const handleChange = (event, index, setValue, setError) => {
let { value, name } = event.target;
name = name.toLowerCase();
if (!value) setError({ ...inputError, [name]: true });
else {
setError({ ...inputError, [name]: false });
setValue(value);
}
};
const arrObj = [
{
name: "Name",
input: "Please enter your name",
onChange: (event, index) =>
handleChange(event, index, setName, setInputError),
helperText: inputError.name && "*Name is Required"
},
{
name: "Email",
input: "enter your email address",
onChange: (event, index) =>
handleChange(event, index, setEmail, setInputError),
helperText: inputError.email && "*Email is Required"
}
];
return (
<div className="App">
{arrObj.map((item, index) => {
let { onChange, input, helperText, name } = item;
return (
<Grid key={index} item xs={12} style={{ textAlign: "center" }}>
<TextField
name={name}
placeholder={input}
required
onChange={(event) => onChange(event, index)}
helperText={helperText}
/>
</Grid>
);
})}
</div>
);
}
Codesandbox Link