DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

8 2 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay