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)
JavaScript
x
44
44
1
import React from "react";
2
import { Formik, Field, Form } from "formik";
3
import { indexBy, map, compose } from "ramda";
4
import { withReducer } from "recompose";
5
6
const MyInput = ({ field, form, handleBlur, rest }) =>
7
<div>
8
<input {field} onBlur={handleBlur} {rest} />
9
{form.errors[field.name] &&
10
form.touched[field.name] &&
11
<div>
12
{form.errors[field.name]}
13
</div>}
14
</div>;
15
16
const indexById = indexBy(o => o.id);
17
const mapToEmpty = map(() => "");
18
19
const EmailsForm = ({ fieldsList }) =>
20
<Formik
21
initialValues={compose(mapToEmpty, indexById)(fieldsList)}
22
validate={values => {
23
// console.log("validate", { values });
24
const errors = { values };
25
return errors;
26
}}
27
onSubmit={values => {
28
console.log("onSubmit", { values });
29
}}
30
handleBlur={e => console.log("bluuuuurr", { e })}
31
render={({ isSubmitting, handleBlur }) =>
32
<Form>
33
<Field
34
component={MyInput}
35
name="email"
36
type="email"
37
handleBlur={handleBlur}
38
/>
39
<button type="submit" disabled={isSubmitting}>
40
Submit
41
</button>
42
</Form>}
43
/>;
44
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:
JavaScript
1
13
13
1
<Field
2
component={MyInput}
3
name="email"
4
type="email"
5
onBlur={e => {
6
// call the built-in handleBur
7
handleBlur(e)
8
// and do something about e
9
let someValue = e.currentTarget.value
10
11
}}
12
/>
13