aixecador
aixecador

Reputation: 876

How to handle Formik's `handleChange` prop?

I get it that Field has an onChange attribute where you can pass the own Formik onChange prop from here: https://jaredpalmer.com/formik/docs/api/formik#handlechange-e-reactchangeevent-any-void.

However, I am struggling to understand where these value[key] is passed, so I can handle the data passed in the form. Found in withFormik(): How to use handleChange that I can pass two callbacks to Formik's onChange prop, but I wonder if there is a better way to handle this.

edit after comments from folks that replied, thanks for that:

My code using these 2 callbacks in the onChange prop in Field:

export default function FormikForm() {
  const onSubmitHandler = (formValues, actions) => {
    console.log(formValues);
    console.log(actions);
  };

  const onChangeHandler = (e) => {
    console.log(e.target.value);
  };

  return (
    <div>
      <h1>This is the Formik Form</h1>
      <Formik
        initialValues={{
          name: "",
          email: "",
          age: ""
        }}
        onSubmit={onSubmitHandler}
        render={props => {
          return (
            <Form>
              <label>
                Name
                <Field
                  name="name"
                  type="text"
                  placeholder="name"
                  onChange={e => {props.handleChange(e); onChangeHandler(e)}}
                />
              </label>
              <button type="submit">Submit</button>
            </Form>
          );
        }}
      />
    </div>
  );
}

Is there a way to do a similar thing as in onSubmitHandler, where Formik automagically outputs the value of the input without having to call these 2 functions in the onChange?

Thanks

Upvotes: 5

Views: 9884

Answers (1)

Chris B.
Chris B.

Reputation: 5763

Every field component receives a field prop which has a value prop containing the value for that field, as well as a form prop containing helper methods that you can use to set the value. I'd need to see the structure of your code to give specific suggestions on how to implement what you want, but you can emulate the default functionality by calling form.setFieldValue(field.name, field.value). In addition, the field prop has this handler built in by default in the field.onChange prop.

Upvotes: 4

Related Questions