I have a dynamic form which can be created with formik's fieldarray. I have no issue generating new form fields and validating them. I am using typescript and below code shows up type error on errors field.
<Formik
enableReinitialize
initialValues={{
formValues: [
{
socialPlatform: "",
url: "",
},
],
}}
onSubmit={(values) => {
console.log(values);
}}
validationSchema={validationSchema}
>
{({ values, handleChange, errors, touched }) => {
return (
<Form>
<FieldArray name="formValues">
{({ push }) => (
<React.Fragment>
{values.formValues.map((formValue, index) => (
<Field
id={`formValues.${index}.socialPlatform`}
name={`formValues.${index}.socialPlatform`}
label="Social Platform"
placeholder="Select Social Media"
options={socialMedias}
value={formValue.socialPlatform}
onChangeHandler={handleChange}
hasError={
errors.formValues[index].socialPlatform &&
touched.formValues[index].socialPlatform
}
errorMessage={errors.formValues[index].socialPlatform}
component={Dropdown}
/>
))}
</React.Fragment>
)}
</FieldArray>
</Form>
);
}}
</Formik>
Below part shows Object is possibly 'undefined' and Property 'socialPlatform' does not exist on type 'string | FormikErrors<{ socialPlatform: string; url: string; }>'. Property 'socialPlatform' does not exist on type 'string'. What should I do?
hasError={
errors.formValues[index].socialPlatform &&
touched.formValues[index].socialPlatform
}
errorMessage={errors.formValues[index].socialPlatform}
Edit: Well since I couldn't find anything meaningful about the issue I had to pass touched and errors props to Input component and handle validation with Formik's getIn function as below;
<Field
id={`formValues.${index}.socialPlatform`}
name={`formValues.${index}.socialPlatform`}
label="Social Platform"
placeholder="Select Social Media"
options={socialMedias}
value={formValue.socialPlatform}
onChangeHandler={handleChange}
handleError={errors}
handleTouched={touched}
component={Input}
/>
and then inside Input component;
import { getIn } from "formik";
const errorMessage = FormikError(handleError, handleTouched, name);
const FormikError = (errors: any, touched: any, fieldName: any) => {
const error = getIn(errors, fieldName);
const touch = getIn(touched, fieldName);
return touch && error ? error : null;
};