Formik: OnChange handler is not working.

Created on 16 Mar 2019  路  3Comments  路  Source: formium/formik

馃悰 Bug report

Current Behavior

I have seen examples of onChange handlers attached to Formik <Field /> components, which appear to fire on input changes

In keeping with these examples, I have added an onChange handler to a <Field /> component. The problem is that this handler function is not being called when the child input changes (it is a <select>).

Expected behavior

When a new option on the <select> is chosen, the handler should fiire

Reproducible example

<Field name={id} onChange={(e: any)=>console.log(e)}>

Suggested solution(s)

Explain how to correctly supply an onChange handler to a Formik form.

Your environment

| Software | Version(s) |
| ---------------- | ---------- |
| Formik | "formik": "^1.5.1",
| React | "react": "^16.4.2",
| TypeScript |
| Browser | chrome 72.0.3626.121
| npm/Yarn | yarn 1.13.0
| Operating System | mac os 10.14

Most helpful comment

Can you try this?

    <Component
      onChange={event => field.onChange(field.name)(event)}
      minEditorHeight={100}
      maxEditorHeight={100}
    />

All 3 comments

onChange is working for me when the onChange handler is in the scope of the Form object but not when in it is passed in as a property. However, handleSubmit is passed in as a property and it works.

const MyForm = props => {
  const { values, touched, errors, handleChange, handleBlur, handleSubmit } = props;

  const localOnChange = () => console.log('local onchange called'); // this works

  return (
    <form onSubmit={handleSubmit} > // handleSubmit is passed in via props and works
      <input type="text" onChange={localOnChange} onBlur={handleBlur} value={values.school} name="school" />
      <input type="text" onChange={handleChange} onBlur={handleBlur} value={values.degreeType} name="degreeType" />
      <button type="submit">Submit</button>
    </form>
  );
};

const FooWithFormik = props => {
  const validate = values => {
    const errors = {};

    if (!values.school) {
      errors.name = 'Required';
    }

    return errors;
  };

  return props.makeForm(validate, MyForm);
};

export default FooWithFormik;

1817

Can you try this?

    <Component
      onChange={event => field.onChange(field.name)(event)}
      minEditorHeight={100}
      maxEditorHeight={100}
    />
Was this page helpful?
0 / 5 - 0 ratings