user10104341
user10104341

Reputation:

ReactJS | Objects are not valid as react children

I am using React with Formik in order to create an manage a form. (Error Handling, submission etc). I am having a little bit of trouble with handling errors from the server.

To solve it, I used Formik's builtin <ErrorMessage />. So, in the first element of the form I added it. Like the one below:

<form onSubmit={handleSubmit}>
          <div className="pb-2">
            <label className="font-weight-bold" htmlFor="username">
              Username <Asterisk />
            </label>
            <Field
              validate={this.debounceUsernameValidation}
              className={classNames('form-control', {
                'is-invalid': errors.username && touched.username
              })}
              placeholder="Username (Required)"
              autoComplete="false"
              name="username"
              type="text"
            />
            {errors.username && touched.username ? (
              <div className="text-danger">{errors.username}</div>
            ) : null}
          </div>
          <ErrorMessage name={errors.username} component="div" className="text-danger small" />
</form>

But I am getting the following error:

Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

I am not sure what I did wrong. Could you help me sovle this, and make me understand what this error is about. I mean the errors that come either from the server or client side, should be an object.

And when React says If you need to be an object, use an array instead. I really don't get it. Thanks for your time.

Error object. This is generated by Yup, which works in conjactions with Formik:

{ "username": "Username is Required", "password": "Password is required", "confirmPassword": "Password Confirmation is Required", "group": "Group is required" }

Upvotes: 3

Views: 2632

Answers (1)

Jose A. Ayll&#243;n
Jose A. Ayll&#243;n

Reputation: 886

You are using <ErrorMessage ... /> wrong. The name prop should be a string with the same value as the key that your error object has. Something like this:

<ErrorMessage component="div" name="username" />
// --> {touched.username && error.username ? <div>{error. username}</div> : null}

If we follow the documentation:

name

name: string Required

A field's name in Formik state. To access nested objects or arrays, name >can also accept lodash-like dot path like social.facebook or >friends[0].firstName

Take a look to the example in the DOC:

https://jaredpalmer.com/formik/docs/api/errormessage

Upvotes: 3

Related Questions