Ionic ReactJS Form Management & Validation With Formik

Ionic ReactJS Form Management & Validation With Formik

Integrating form and form validation in Ionic Framework React JS Application using Formik and Yup.

ยท

2 min read

Integrating form and form validation in Ionic Framework React JS Application using Formik and Yup.

In the video we also show the use of formik useFormikContext()

The video demonstrates the use of additional ionic components in react applications, the source code below covers the basic pattern that used to make it all work.

Quick Video Summary

Create the validation schema with yup

const validationSchema = yup.object({
  color: yup
    .string()
    .nullable()
    .required("Color is required"),
});

We wrap the whole content section with the Formik component and then get access to all of the formikProps in the render method.

To get everything to place nice with Ionic React Components we let formik handle the values formikProps.values.color and the change events formikProps.handleChange

when the form meets all of the validation criteria specified in the validation schema, the call to submit the form is also processed by formik formikProps.handleSubmit.

<Formik
  initialValues={{
    color: null
  }}
  validationSchema={validationSchema}
  onSubmit={values => {
    alert(JSON.stringify(values, null, 2));
  }}
>
  {formikProps => (
    <IonContent>
      <form onSubmit={formikProps.handleSubmit}>
        <IonItem>
          <IonLabel>Select Color</IonLabel>
          <IonSelect
            name="color"
            value={formikProps.values.color}
            onIonChange={formikProps.handleChange}
          >
            <IonSelectOption value="brown">Brown</IonSelectOption>
            <IonSelectOption value="blonde">Blonde</IonSelectOption>
            <IonSelectOption value="black">Black</IonSelectOption>
            <IonSelectOption value="red">Red</IonSelectOption>
          </IonSelect>
        </IonItem>
        <p className="error">
          {formikProps.touched.color && formikProps.errors.color}
        </p>
        <IonButton type="submit">SAVE</IonButton>
      </form>

    </IonContent>
  )}
</Formik>

Full Source Code in Stackblitz

๐Ÿ’ฅ Additional Content


๐Ÿ’ฅ Social Media


ย