I was getting invalid hook error on rendering Formik.
UI code:
import React from 'react';
import PropTypes from 'prop-types';
import FormGroup from '../../molecules/Form/FormGroup';
import FormAction from '../../molecules/Form/FormAction';
import ControlController from '../../../controllers/ControlController';
import { Formik, Form } from 'formik';
const ControlForm = ({ type }) => (
<Formik
initialValues={{
name: ''
}}
onSubmit={async values => {
console.log(values);
}}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting
}) => (
<Form>
<FormGroup
name="control"
label="Controle"
type="text"
placeholder="Digite o nome do controle"
handleChange={handleChange}
handleBlur={handleBlur}
value={values.name}
/>
<FormAction
onClear={onClear}
handleSubmit={handleSubmit}
className="mt-1"
/>
</Form>
)}
</Formik>
);
Error:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
at resolveDispatcher (/home/kali/Code/poslisa/node_modules/react/cjs/react.development.js:1590)
at Object.useRef (/home/kali/Code/poslisa/node_modules/react/cjs/react.development.js:1626)
at useFormik (node_modules/formik/dist/formik.cjs.development.js:367)
at Formik (node_modules/formik/dist/formik.cjs.development.js:1092)
at renderWithHooks (renderer.dev.js:38541)
at mountIndeterminateComponent (renderer.dev.js:41221)
at beginWork (renderer.dev.js:42345)
at HTMLUnknownElement.callCallback (renderer.dev.js:23904)
at Object.invokeGuardedCallbackDev (renderer.dev.js:23953)
at invokeGuardedCallback (renderer.dev.js:24008)
chrome-extension://react-developer-tools/build/react_devtools_backend.js:6 The above error occurred in the <Formik> component:
in Formik (at ControlForm.jsx:9)
in ControlForm (at ControlAdd.jsx:11)
in div (created by Row)
in Row (at FormTemplate.jsx:9)
in div (created by Container)
in Container (at DefaultTemplate.jsx:12)
in DefaultTemplate (at FormTemplate.jsx:8)
in FormTemplate (at ControlAdd.jsx:10)
in ControlAdd (created by Context.Consumer)
in Route (at Routes.tsx:19)
in Switch (at Routes.tsx:16)
in App (at Routes.tsx:15)
in Routes (at Root.jsx:11)
in Router (created by ConnectedRouter)
in ConnectedRouter (created by Context.Consumer)
in ConnectedRouterWithContext (created by ConnectFunction)
in ConnectFunction (at Root.jsx:10)
in Provider (at Root.jsx:9)
in Root (created by HotExportedRoot)
in AppContainer (created by HotExportedRoot)
in HotExportedRoot
in AppContainer (at app/index.tsx:15)
React will try to recreate this component tree from scratch using the error boundary you provided, AppContainer.
@LuigiPolidorio What was the issue? Running into the same issue in my project
@bduff9 I thought I had resolved it, but I couldn't.
So I did it manually with hooks.
@bduff9 I thought it could be an environment issue. But I couldn't explore it further.
can you reproduce this in CodeSandbox? this error is typical of either
a) configuring the webpack / npm environment incorrectly
b) calling a hook from the render function of another component, like this:
const MyComponent = () => {
const [state, setState] = React.useState(false);
return <Formik>
{() => {
setState(true); // error, call this within a `useEffect()` or event callback like onClick
}}
</Formik>
}
For me, this was user error on my part. My package.json didn't save so I didn't have the formik package. Odd that it showed as invalid hook, but everything is working now.
This worked for me:
cd formik/packages/formik
yarn install
yarn link
cd MY_PROJECT
yarn link "formik"
yarn link
cd node_modules/react
yarn link
cd ../react-dom
yarn link
cd formik/packages/formik
yarn link react
yarn link react-dom
yarn link MY_PROJECT
Hi I am having a similar issue .
Calling the below Form component in render of Formik ...
import React from 'react';
import Cx from 'classnames';
import { scrollTo, stringToClassOrKey } from '../../helpers/Utilities';
import { FormikErrors, Form as FormikForm } from 'formik';
import { Spinner } from '../spinner/Spinner';
import { Alert } from '../alert/Alert';
import './form.scss';
import { Collapsable } from '../collapsable/Collapsable';
interface IProps {
name: string;
compact?: boolean;
errors: FormikErrors
isSubmitting: boolean;
isValidating: boolean;
isLoading?: boolean;
children: JSX.Element;
className?: string;
}
interface IState {
hasValidated: boolean;
}
interface IFormButtonsProps {
positive: JSX.Element[];
negative?: JSX.Element[];
}
export const FormButtons = (props: IFormButtonsProps): JSX.Element => {
const { positive, negative } = props;
return (
export const Form = (props: IProps): JSX.Element => {
const { isLoading, isSubmitting, isValidating, errors, compact, className, children } = props;
const formErrorsEl = React.createRef
console.log('in here');
/useEffect(() => {
/if (props.isValidating === true && hasValidated === false) {
setValidated(true);
}
console.log('here');
});*/
// const [hasValidated, setValidated] = React.useState
const renderErrors = (errors: FormikErrors
const errorList: JSX.Element[] = [];
for (const errorKey in errors) {
if (errors.hasOwnProperty(errorKey)) {
const error: string | undefined = errors[errorKey];
if (error) {
errorList.push(
<li className="form__errors-item" key={stringToClassOrKey(error)}>
<a
className="form__errors-anchor"
href={`#${errorKey}`}
onClick={(e: React.MouseEvent<HTMLAnchorElement>): void => {
e.preventDefault();
scrollTo(errorKey, true);
}}
>
{error}
</a>
</li>,
);
}
}
}
return (
<Alert type="error" className="form__errors-alert">
<strong>Please fix the following {errorList.length > 1 ? `${errorList.length} errors` : 'error'} to continue.</strong>
<ul className="form__errors-list">{errorList}</ul>
</Alert>
);
};
if (isSubmitting && isValidating && errors && Object.keys(errors).length > 0 && formErrorsEl.current) {
scrollTo(formErrorsEl.current, true);
}
const formClasses: string = Cx(form, {
'form--invalid': errors && Object.keys(errors).length > 0,
'form--compact': compact,
[${className}]: className,
});
return (
@sujalanilagiri there are some formatting issues with your code above. Please fix the formatting and I'll see if I can pinpoint your issue.
I ran into this issue, reduced it down to smallest test case and wasn't doing anything particularly silly. Checked sources and found React in there twice.
To fix, in the developer console check through sources to see if you have React loaded twice. If you do, and you're using Webpack, you can fix this with:
resolve: {
alias: {
react: path.resolve('./node_modules/react'),
},
},
Most helpful comment
This worked for me: