Formik: onBlur handler on useField hook

🙌 onBlur handler and real time validation on useField hook

Hello!

I started learning and practicing Formik, but ran into one problem. My project uses custom placeholders that move up with the focus field.

What do I need for this❓

💪 Started to do

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.

Prepared Sandbox 👉 Sandbox

🙏 Please tell me what and where I missed, how can this be implemented? Thanks!

Upvotes: 2

Views: 6497

Answers (2)

Another solution, they are the same, but this option is more beautiful and well readable!

Thanks Kinbaum!

In your handleBlur function, you can call field.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);
    }
}

GitHub Issue Answer

Working code 👉 Sandbox Link

Upvotes: 1

Ant
Ant

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

Related Questions