React.js: submit form programmatically does not trigger onSubmit event React.js: submit form programmatically does not trigger onSubmit event reactjs reactjs

React.js: submit form programmatically does not trigger onSubmit event


I have success with this. This triggers the handleSubmit upon clicking. Hope this helps.

<form  onSubmit={this.handleSubmit}  ref={ (ref) => { this.form = ref; } }>    <a onClick={ () => { this.form.dispatchEvent(new Event('submit')) } }>        Validate    </a></form>

Found from here: https://github.com/facebook/react/issues/6796


Your current onSubmit is bound to the triggering of a React SyntheticEvent and not the native form submit event. That explains why this.refs.formToSubmit.submit(); is not triggering your handler. As far as I know, trying to manually trigger that SyntheticEvent is not a recommended or worthwhile pursuit.

I believe the idiomatic way to accomplish this is to structure the JSX/HTML to use a <button> or <input> of type submit. Either of those will trigger your handleSubmit handler. In my opinion, it will reduce complexity, consolidate your handlers, and seems to be your best solution.

e.g.

  • <input type="submit" value="Validate" />
  • <button type="submit">Validate</button>


Update 2021

The solution from the accepted answer didn't work for me so I decided to update this topic.

React 16 (and older)

In the original answer, the second parameter of the Event constructor is missing. Without {cancelable: true} parameter, the preventDefault() method cannot be run.

<div>    <form onSubmit={e => e.preventDefault()} ref={ref => this.form = ref}>        <input name="tmp" />    </form>    <button onClick={e => this.form.dispatchEvent(        new Event("submit", { cancelable: true })    )}>        Submit form    </button></div>

React 17 (and probably newer versions in the future)

In the current version of React (17), there has been a quire big change in event delegation (details here). Thus, the solution above needs a small improvement to work with this version of the library. This change is the bubbles: true parameter. Working code would look like this:

<div>    <form onSubmit={e => e.preventDefault()} ref={ref => this.form = ref}>        <input name="tmp" />    </form>    <button onClick={e => this.form.dispatchEvent(        new Event("submit", { cancelable: true, bubbles: true })    )}>        Submit form    </button></div>