I have a form where the user needs to answer 3 questions to be able to register a new password. All fields are mandatory, and the user is unable to send the data to the server until the 3 questions are answered.
My question is how to handle input field errors with only one function? I currently perform a function for each of the fields. And this is not very good at performance levels.
For example, with just one function I can get the values entered in all input fields:
const handleChangeField = (field) => (event) => {
const value = event?.target?.value || "";
setData((prev) => ({ ...prev, [field]: value }));
};
Can you tell me if it is possible to create a function similar to the one above, but to handle errors? In this moment that's what I'm doing:
<TextField
label="What is your mother's name?"
className={classes.input}
error={hasErrorMother}
helperText={hasErrorMother ? "Required field*" : ""}
value={data.motherName}
onInput={(event) =>
event.target.value.length > 0
? setHasErrorMother(false)
: setHasErrorMother(true)
}
onChange={handleChangeField("motherName")}
/>
I handle errors for each of the fields within onInput.
Here's the code I put into codesandbox
Thank you very much in advance.