Nitesh Rana
Nitesh Rana

Reputation: 512

Formik hooks "useField" throws error stating that the component is not a React function component

I am trying to create a reusable input component in React v16.12.0 and formik version 2.1.2. Below is the code for input component.

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

const input = ({label, ...props}) => {
    const [field, meta, helpers] = useField(props);
    return (
        <div>
            <label>
                {label}
            </label>
            <input {...field} {...props} />

        </div>
    )
}

export default input;

When I try to integrate this component inside any form it gives me below error. The integration code is given below :

<Formik initialValues={{
            firstName: '',
            lastName:''
        }}
        onSubmit={(data) => {

            console.log(data)
        }}>
            {({values, isSubmitting})=>(
                <Form>
                    <Input label="hello" name="firstName" />
                    <button type="submit">Submit</button>
                    <pre>
                        {JSON.stringify(values)}
                    </pre>
                </Form>
            )
            }
        </Formik>

Error Message

Upvotes: 1

Views: 817

Answers (1)

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

React components must be named in PascalCase

The error is because you haven't followed the proper naming convention for react components. Any components, be it functional or Class, should be named in PascalCase. Try renaming your input component definition, like so:

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

//  'Input' not 'input"
const Input = ({label, ...props}) => {
    const [field, meta, helpers] = useField(props);
    return (
        <div>
            <label>
                {label}
            </label>
            <input {...field} {...props} />

        </div>
    )
}

export default Input; // <---  'Input' not 'input"

Upvotes: 2

Related Questions