Formik, useField() in child component?

Viewed 6857

I have a separate module that I'm working on, this module is meant to contain formik supporting HTML input elements.

The issue is I'm unable to use the useFields() hook since my module component doesn't connect to the formik context.

Here's my component that resides in a different module:

import React from "react";
import PropTypes from "prop-types";
import { useField } from "formik";

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

TextField.propTypes = {
  name: PropTypes.string.isRequired,
  label: PropTypes.string,
  showErrors: PropTypes.bool
};

TextField.defaultProps = {
  label: "",
  showErrors: true
};

export default TextField;

and here is my Formik form:

<Formik
      initialValues={{
        firstName: "firstName"
      }}
      onSubmit={(values, actions) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }, 1000);
      }}
    >
      {formik => (
        <Form>
          <TextField name="firstName" />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>

No matter what I do I get the following error:

TypeError: Cannot read property 'getFieldProps' of undefined

Anyone have an idea what I'm doing wrong?

1 Answers

Looking at the useField docs I would expect:

<input {...field} {...props} />

The input component does not expect the {...meta} props.

other than that I could not reproduce your error.

Related