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 ?
Solution#1: you're listen to a DOM event, and you will need to access the DOM to get information, which is leaning towards the uncontrolled components pattern. Solution#2: you're listen to the state changes without touching DOM, which is leaning towards the controlled components pattern.
Now we must write the handleChange method to update the state with user inputs: handleChange = ({ target }) => { const { formValues } = this. state; formValues[target.name] = target. value; this.
We can reset the form by using the resetForm() method of formik. We can register it on the onClick event of the reset button.
useFormik() is a custom React hook that will return all Formik state and helpers directly. Despite its name, it is not meant for the majority of use cases. Internally, Formik uses useFormik to create the <Formik> component (which renders a React Context Provider).
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 ... }} />
See https://github.com/jaredpalmer/formik/issues/157
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With