blurred-green

Problem

I’ve been working with the deliciously productive React Hooks API recently, and have been using React Hook Form as my go to form abstraction.

There was one issue I faced lately however that bothered the heck out of me: When the user hits enter on the keyboard, for some mysterious reason I was not able to get the input to blur.

Even if there was no validation errors, and the data was successfully saved, the input just. would. not. blur. I was desperate enough to even try a hack where I tried to force some other element to focus, in order to blur the element I needed to.

Solution

The solution is as simple as manipulating the browser DOM directly, instead of relying on a React Hook Form method:

document.activeElement.blur()

An example of how that would work in a simple form:

import { useForm } from 'react-hook-form';

const FormComponent = () => {  
  const { register, handleSubmit } = useForm();
  const handleSubmit = (data) => {
    // ... do something with the data 
    document.activeElement.blur(); // <-- trigger blur
  };

  return (
    <form
      onSubmit={handleSubmit}
      <input id="key1" {...register("key1")}></input>
    </form>
  );
};

export default FormComponent;

Why isn’t this part of the library?

Your guess is as good as mine, but I’m guessing it might have something to do with how straightforward it is to achieve this outside the library.