How to prevent page reload using form.submit() to submit as a method in ReactJs

Tags: , ,



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

Answer

Use 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.



Source: stackoverflow