1

How to prevent page refreshing on firing form submission programmatically in ReactJS? I've tried this code:

const myForm = () =>
    <form onBlur={(e) => {
      if(!e.relatedTarget || (e.relatedTarget.form !== e.activeTarget)) 

        e.currentTarget.submit((e) => {
          e.preventDefault();// page reloads before this callback
          debugger
        });
      }
    }}
    onSubmit={(e) => {
      e.preventDefault();//// page reloads before this event
      debugger
    }}>
    ...
 </form>

My goal is to submit form onBlur from this form (when a user fills all the fields and clicks outside of the form)

I've already checked these solutions but they dont work:

Prevent page reload when submit

I dont consider iframes Submit form without page reloading

Alexey Nikonov
  • 4,958
  • 5
  • 39
  • 66

1 Answers1

3

You should use e.currentTarget.requestSubmit() (docs). Read about differences with submit method here.

Or you may simply define a submit handler function and provide it to both onBlur and onSubmit form properties.

const handleSubmit = (ev) => {
  ev.preventDefault()
  ... 
}

return (
  <form 
    onBlur={(ev) => if (shouldSubmit(ev)) handleSubmit(ev)}
    onSubmit={handleSubmit}
  >
  ...
  </form>
)

Without resorting to native form submission. If your use case allows that.

Leeuw
  • 53
  • 8
aleksxor
  • 7,535
  • 1
  • 22
  • 27
  • >"Or you may simply define a submit handler function and provide it to both" - Yeap, I've though about this, but the project uses Final-Form lib and its validation logic is tied with onSubmit event. – Alexey Nikonov Jun 07 '21 at 06:32