Вот рабочий код с несколькими проверками электронной почты и ошибками. Я использовал Formik FieldArray для обработки нескольких писем. Вы можете заменить свой код этим в своей песочнице для тестирования.
import React from "react";
import { TextField, IconButton } from "@material-ui/core";
import {
AddCircleOutlined as AddCircleOutlinedIcon,
IndeterminateCheckBox as IndeterminateCheckBoxIcon
} from "@material-ui/icons";
//FORMIK
import { Formik, FieldArray, getIn, ErrorMessage } from "formik";
import * as Yup from "yup";
export default function UnitsDrawer(props) {
const callAPI = e => {
console.log(e.name);
console.log(e.email);
};
const testSchema = Yup.object().shape({
name: Yup.string().required("Customer name is required"),
email: Yup.array().of(
Yup.string()
.email("Enter a valid email")
.required("Email is required")
)
});
const initialValues = {
name: "",
email: [""]
};
const formRef = React.useRef();
return (
<div>
<Formik
innerRef={formRef}
validationSchema={testSchema}
initialValues={initialValues}
onSubmit={(values, actions) => {
actions.setSubmitting(false);
callAPI(values);
}}
>
{({
handleChange,
handleBlur,
values,
errors,
touched,
handleSubmit,
isSubmitting,
}) => {
return (
<>
<div>
<TextField
label="Customer Name"
name="name"
margin="normal"
variant="outlined"
error={errors.name && touched.name}
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
fullWidth
/>
<ErrorMessage name="name" component="div" />
</div>
<FieldArray name="email">
{({ push, remove }) =>
values.email.map((field, index) => (
<div key={`${index}`} className="dynamic-fields">
<div>
<TextField
label="Email"
variant="outlined"
className="input-item"
error={
getIn(touched, `email.${index}`) &&
getIn(errors, `email.${index}`)
}
name={`email.${index}`}
value={values.email[index]}
onChange={handleChange}
onBlur={handleBlur}
fullWidth
/>
<ErrorMessage name={`email.${index}`} component="div" />
</div>
<IconButton
aria-label="filter list"
className="add-icon"
onClick={() => {
push("");
}}
>
<AddCircleOutlinedIcon color="primary" />
</IconButton>
{values.email.length > 1 && (
<IconButton
aria-label="filter list"
className="add-icon"
onClick={() => {
remove(index);
}}
>
<IndeterminateCheckBoxIcon />
</IconButton>
)}
</div>
))
}
</FieldArray>
</>
);
}}
</Formik>
</div>
);
}