Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  162] [ 7]  / answers: 1 / hits: 116603  / 7 Years ago, fri, january 26, 2018, 12:00:00

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 ?


More From » forms

 Answers
7

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


[#55345] Wednesday, January 24, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
halleyb

Total Points: 604
Total Questions: 96
Total Answers: 115

Location: Tokelau
Member since Wed, Oct 14, 2020
4 Years ago
;