Reputation: 43
Hello!
I started learning and practicing Formik, but ran into one problem. My project uses custom placeholders that move up with the focus field.
onFocus
and onBlur
To do this, I made a component CustomField
with the useField()
hook. Works, cool 😎
But later he noticed that real time validation and error messages stopped working 🤦♂️. Because I redefined onBlur
handler. After searching, studying the problem did not find a solution using onBlur
handler without interfering with Formik.
🙏 Please tell me what and where I missed, how can this be implemented? Thanks!
Upvotes: 2
Views: 6497
Reputation: 43
Another solution, they are the same, but this option is more beautiful and well readable!
Thanks Kinbaum!
In your
handleBlur
function, you can callfield.onBlur
and pass the synthetic event to it. Something like this:
function handleBlur(e) {
// Call the Formik onBlur event before your custom stuff
field.onBlur(e);
if (!field.value.length > 0) {
onFocus(false);
}
}
Working code 👉 Sandbox Link
Upvotes: 1
Reputation: 208
Not sure if this is the best solution.
My work around for this is to make continue to make use of the onBlur function provided by formik, but also to use your function. This is done by passing the field onBlur function to your handleBlur function and calling it on execution. You can see the changes in this sandbox.
So the two areas of change is this line
onBlur={e => handleBlur(field.onBlur, e)}
and
function handleBlur(formikBlur, event) {
if (!(field.value.length > 0)) {
onFocus(false);
}
formikBlur(event);
}
To make use of the formik onBlur function :D Good luck
Here is the code sandbox
https://codesandbox.io/s/agitated-gagarin-g07zk?fontsize=14&hidenavigation=1&theme=dark
Upvotes: 2