Search code examples
reactjsobjectdefaultformik

"object Object" showing as input value with Formik forms on ReactJS


With Formik, my input shows an [object Object] value instead of behaving in a standard manner.

Code is here.

import React from "react";
import ReactDOM from "react-dom";
import { Formik, Field, Form, ErrorMessage } from "formik";
import * as Yup from "yup";
import "./styles.css";

const SignupForm = () => {
  return (
    <Formik
      initialValues={{ email: "" }}
      validationSchema={Yup.object({
        email: Yup.string()
          .email("Mauvais e-mail")
          .required("Champ requis")
      })}
      onSubmit={values => {
        alert(JSON.stringify(values, null, 2));
      }}
    >
      <Form>
        <label htmlFor="email">Email</label>
        <ErrorMessage name="email" />
        <br />
        <Field name="email" type="email" />
        <button type="submit">OK</button>
      </Form>
    </Formik>
  );
};

ReactDOM.render(<SignupForm />, document.querySelector("#root"));

Solution

  • Formik matches the initial values to the name of the field, not the id.

    Try using this as your Field:

    <Field name="email" id="email" type="email" />

    import React from "react";
    import ReactDOM from "react-dom";
    import { Formik, Field, Form, ErrorMessage } from "formik";
    import * as Yup from "yup";
    import "./styles.css";
    
    const SignupForm = () => {
      return (
        <Formik
          initialValues={{ email: "" }}
          validationSchema={Yup.object({
            email: Yup.string()
              .email("Mauvais e-mail")
              .required("Champ requis")
          })}
          onSubmit={values => {
            alert(JSON.stringify(values, null, 2));
          }}
        >
          {props => (
            <Form>
              <label htmlFor="email">Email</label>
              <ErrorMessage name="email" />
              <br />
              <Field
                name="email"
                id="email"
                type="email"
                onChange={e => {
                  props.setTouched({ email: true });
                  props.handleChange(e);
                }}
              />
              <button type="submit">OK</button>
            </Form>
          )}
        </Formik>
      );
    };
    
    ReactDOM.render(<SignupForm />, document.querySelector("#root"));
    
    

    You can also check the docs for more info on Field