I need to trigger a reactjs form submission from a button eventhandler to a fixed URL.
So far, I have seen SO examples (e.g. here) of form submission with a button of type submit
and with buttons of type button
and onClick
eventhandler, which seems to need a form with onSubmit
eventhandler (see examples below)
With submit button inside form
Working!
render(){
return(
<div>
<form id="form1" method="post" action="http://localhost:3000/">
<label>
Name:
<input type="text" name="name" enctype='text/plain' value={this.state.data} />
<button type="submit">Submit inside form</button>
</label>
</form>
With submit button and eventhandler
Also working!
<form id="form3" method="post" onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name="name" enctype='text/plain' value={this.state.data} />
<button type="submit">submit</button>
</label>
</form>
<button
onClick={ () =>
document.getElementById('form3').dispatchEvent(new Event('submit'))}
>
This works
</button>
I would just need to trigger a simple submit with an action
from a button with an eventhandler
, like in the not-working example below.
<form id="form4" method="post" action="http://localhost:3000/"
onSubmit={this.doNothingLetActionDoTheJob}>
<label>
Name:
<input type="text" name="name" enctype='text/plain' value={this.state.data} />
<button type="submit">submit</button>
</label>
</form>
<button
onClick={ () =>
document.getElementById('form4').dispatchEvent(new Event('submit'))}
>
This does not work
</button>
Is this possible? If yes, what am I doing wrong?