reactjsformsonblur

Apply onBlur to form elements but not to the reset button


I'm working with a form that has onBlur defined on it. I would now like to add a button within the form to reset it. But when I added the button, it attached the onBlur to it, so now clicking the button doesn't work and it only executes when I tab away from the button.

Here's a very condensed version of my code:

<form onBlur={handleBlur} onReset={onClear}>
  <label>
    Input1
    <input type="text"/>
  </label>
  <label>
    Input2
    <input type="text"/>
  </label>
  <button type="reset">Reset</button>
</form>

I imagine one solution would be to attach the onBlur to each input, instead of on the <form>, but that would be a large refactor based on the code I haven't shown. So I am wondering if there is a different way.


Solution

  • you need to stop the propagation of blur event from button element to form element. This is a javascript concept called event propagation. Basically every event will propagate from their child to parent. So u can prevent it using event.stopPropagation()

    <form onBlur={handleBlur} onReset={onClear}>
      <label>
        Input1
        <input type="text" />
      </label>
      <label>
        Input2
        <input type="text" />
      </label>
      <button onBlur={(e) => e.stopPropagation()} type="reset">
        Reset
      </button>
    </form>;