DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

How to access Formik props with useFormikContext() hook

There's a super easy way of accessing props and helpers like handleSubmit, handleChange, handleBlur, values, errors, etc in Formik. Just wrap your components inside the <Formik>...</Formik> context and you can use the hook to get access to all the props.

Example:

 import React from 'react';
 import { useFormikContext, Formik, Form, Field } from 'formik';

 const AutoSubmitToken = () => {
   // Grab values and submitForm from context
   const { values, submitForm } = useFormikContext();
   React.useEffect(() => {
     // Submit the form imperatively as an effect as soon as form values.token are 6 digits long
     if (values.token.length === 6) {
       submitForm();
     }
   }, [values, submitForm]);
   return null;
 };

 const TwoFactorVerificationForm = () => (
   <div>
     {/* .... */}
     <Formik
       initialValues={{ token: '' }}
       validate={values => {
         {/* ... */}
       }}
       onSubmit={(values, actions) => {
         {/* ... */}
       }}
     >
       <Form>
         <Field name="token" type="tel" />
         <AutoSubmitToken />
       </Form>
     </Formik>
   </div>
 );
Enter fullscreen mode Exit fullscreen mode

Full example: https://formik.org/docs/api/useFormikContext

Top comments (0)