DEV Community

MorenoMdz
MorenoMdz

Posted on

React(&Native) Submit and Validate with Formik from outside the Form

Let's say you need to call the Submit event from Formik from outside the form for whatever reason, the form is in an external component for example. The useRef hook will help here:

import React, { useState, useRef } from 'react';

const YourComponent = () => {
  const formRef = useRef();
  const [input, setInput] = useState({});
  const [step, setStep] = useState(1);

  const saveInput = () => {
    if (formRef.current) {
      formRef.current.handleSubmit();
      if (formRef.current.isValid) {
        setStep(2);
      }
    }
  };

  const ValidationSchema = Yup.object().shape({
    name: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('Required'),
  });

  return (
    <View>
      <Formik
        initialValues={{
          name: '',
          description: '',
          points: '',
          redemptionsTotal: '',
          redemptionsPerUser: '',
        }}
        validationSchema={QrCodeSchema}
        validateOnChange={true}
        validateOnBlur={false}
        validateOnMount
        onSubmit={(values) => setInput(values)}
        innerRef={formRef}
      >
        {({ handleChange, handleBlur, values, touched, errors }) => {
          return (
            <FormInput
              allowFontScaling={false}
              onChangeText={handleChange('name')}
              onBlur={handleBlur('name')}
              value={values.name}
              error={errors.name}
              touched={touched.name}
              name="name"
              placeholder="TITLE"
              returnKeyType="next"
              blurOnSubmit={false}
              style={styles.inputStyle}
            />
          );
        }}
      </Formik>
      <YourActionsComponent>
        <Button name="submit" title={'Define Dates'} onClick={() => saveInput()} style={styles.stepButton} />
      </YourActionsComponent>
    </View>
  );
};

In this small example, where we have a wizard-like modal where the user fills a few inputs in every step, we set that when the form mounts it will check if there are any invalid inputs and it won't let the step change happen if so.

We save the form data from Formik into the form ref, there we have access to all the important state from the form (run a console.log(formRef.current) to see more) and you can programmatically call the submit from outside this way.

For more info about Formik validation https://formik.org/docs/guides/validation

Top comments (0)