skip to Main Content

Error: React Hook "useFormik" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function

enter image description here

i cut this line from line 75 to 92 and paste in line 5 but same error (HOW TO SOLVE THIS)

2

Answers


  1. In the picture, I see you have used the useFormik hook outside the function component. But you have to use this inside a React Function Component

     // import required modules & libraries
     import React from 'react';
     import { useFormik } from 'formik';
     
    // A react function component
     const SignupForm = () => {
       // here it is inside the `SignupForm` component
       // useFormik Hook Start
       const formik = useFormik({
         initialValues: {
           firstName: '',
           lastName: '',
           email: '',
         },
         onSubmit: values => {
           alert(JSON.stringify(values, null, 2));
         },
       });
       // useFormik Hook End
    
       // Rnder the form
       return (
         <form onSubmit={formik.handleSubmit}>
           <label htmlFor="firstName">First Name</label>
           <input
             id="firstName"
             name="firstName"
             type="text"
             onChange={formik.handleChange}
             value={formik.values.firstName}
           />
           <label htmlFor="lastName">Last Name</label>
           <input
             id="lastName"
             name="lastName"
             type="text"
             onChange={formik.handleChange}
             value={formik.values.lastName}
           />
           <label htmlFor="email">Email Address</label>
           <input
             id="email"
             name="email"
             type="email"
             onChange={formik.handleChange}
             value={formik.values.email}
           />
           <button type="submit">Submit</button>
         </form>
       );
     };
    
    Login or Signup to reply.
  2. You need to do something like this:

     const MyForm = (handleSubmit, setValues, ...) => { 
        // the hook needs to be used like this 
       const formik = useFormik({
         initialValues: {
         NameOftheUPSIProject: '',
         InformationSharedBy: '',
         InsiderTypes: '',
         ..
        },
       onSubmit: values => {
         console.log(JSON.stringify(values));
       },
      });
    } 
    

    As seen in the above code, you can use the useFormik hook either inside a React functional component or a React hook function.

    Reference doc: useFormik

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search