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