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
i cut this line from line 75 to 92 and paste in line 5 but same error (HOW TO SOLVE THIS)
2
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
useFormik
// 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> ); };
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.
functional
hook
Reference doc: useFormik
Click here to cancel reply.
2
Answers
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 ComponentYou need to do something like this:
As seen in the above code, you can use the
useFormik
hook either inside a Reactfunctional
component or a Reacthook
function.Reference doc: useFormik