In my form, I am using Formik/Yup for Validation. Currently, this works in my form perfectly:
export default function AddUserPage() {
const [firstName, setFirstName] = useState("");
const [email, setEmail] = useState("");
return (
<div>
<Formik
initialValues={{ firstName: "", email: "" }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
validationSchema={schema}
>
{props => {
const {
values: { firstName, lastName, email, password, phone },
errors,
touched,
handleChange,
isValid,
setFieldTouched
} = props;
const change = (name: string, e: any) => {
e.persist();
handleChange(e);
setFieldTouched(name, true, false);
};
return (
<div className="main-content">
<form style={{ width: "100%" }}>
<div>
<TextField
variant="outlined"
margin="normal"
id="firstName"
name="firstName"
helperText={touched.firstName ? errors.firstName : ""}
error={touched.firstName && Boolean(errors.firstName)}
label="First Name"
//onChange={e => setFirstName(e.target.value)}
value={firstName}
onChange={change.bind(null, "firstName")}
/>
<br></br>
<TextField
variant="outlined"
margin="normal"
id="email"
name="email"
helperText={touched.email ? errors.email : ""}
error={touched.email && Boolean(errors.email)}
label="Email"
value={email}
onChange={change.bind(null, "email")}
/>
<br></br>
</div>
</form>
</div>
);
}}
</Formik>
</div>
);
}
However, instead of typing everything, I want to map my text fields. How could I map my text fields?
I tried something like this but I get errors for helperText and error properties:
{[{ label: "First Name", state: firstName , type: "text", function: setFirstName},
{ label: "Email", state: email , type: "text", function: setEmail},
]}.map((item, index) => (
<div>
<TextField
id="outlined-basic"
key={index}
label={item.label}
variant="outlined"
type= {item.type}
helperText= {touched[item.state] ? errors[item.state] : ""}
onChange={change.bind(null, state)}
/>
<br></br><br></br>
</div>
)
Here, I get an error on helper text that:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'FormikTouched<{ firstName: string; lastName: string; email: string; password: string; phone: string; }>'
I tried adding this as well but this also gives me an error:
helperText = {touched.item.state}
touched.{item.state}
this is not valid JS. – evolutionxboxtouched[item.state]
– evolutionxbox