I’m starting out with the formik library for react, and I can’t figure out the usage of the props handleChange and handleBlur.
According to the docs, handleBlur can be set as a prop on a <Formik/>
, and then has to be passed manually down to the <input/>
.
I’ve tried that, with no success : (I’m keeping the code about handleBlur for more clarity)
import React from "react"; import { Formik, Field, Form } from "formik"; import { indexBy, map, compose } from "ramda"; import { withReducer } from "recompose"; const MyInput = ({ field, form, handleBlur, ...rest }) => <div> <input {...field} onBlur={handleBlur} {...rest} /> {form.errors[field.name] && form.touched[field.name] && <div> {form.errors[field.name]} </div>} </div>; const indexById = indexBy(o => o.id); const mapToEmpty = map(() => ""); const EmailsForm = ({ fieldsList }) => <Formik initialValues={compose(mapToEmpty, indexById)(fieldsList)} validate={values => { // console.log("validate", { values }); const errors = { values }; return errors; }} onSubmit={values => { console.log("onSubmit", { values }); }} handleBlur={e => console.log("bluuuuurr", { e })} render={({ isSubmitting, handleBlur }) => <Form> <Field component={MyInput} name="email" type="email" handleBlur={handleBlur} /> <button type="submit" disabled={isSubmitting}> Submit </button> </Form>} />;
What is wrong with this approach ? How are handleBlur and handleChange actually supposed to be used ?
Advertisement
Answer
You’ll need to remove the first handleBlur
from Formik
as blur event is only valid on the field level and do something like the following in your Field element:
<Field component={MyInput} name="email" type="email" onBlur={e => { // call the built-in handleBur handleBlur(e) // and do something about e let someValue = e.currentTarget.value ... }} />