Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik, useField() in child component?

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?

like image 588
MMStarr Avatar asked Mar 02 '20 16:03

MMStarr


People also ask

What does Formik handleBlur do?

handleBlur is how touched is actually updated (or at least one of the ways). If your input isn't passed an onBlur handler connecting to Formik's state, the touched state won't be updated. If you blur the first input, touched is updated. If you blur the second input, touched is not updated.

What is useField Formik?

useField is a custom React hook that will automagically help you hook up inputs to Formik. You can and should use it to build your own custom input primitives.

How do I get form value in Formik?

The Field component in Formik is used to automatically set up React forms with Formik. It's able to get the value by using the name attribute, it uses the name attribute to match up the Formik state and it is always set to the input element. That can easily be changed by specifying a component prop.


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.

like image 157
Ruben Van Den Abeele Avatar answered Oct 19 '22 20:10

Ruben Van Den Abeele