Sylar Sylar - 5 months ago 6
Javascript Question

Form submits on wrong button click in React

Strange, my entire component keeps submitting by clicking the incorrect button.

The layout:

B Component
is inside
Component A
.
A Component
has the form.
B Component
triggers the form submit and I dont know why.

In the return function of A Component:

<form action... method...>
<BComponent />
<button type="submit">Submit</button>
</form>


B Component:

...

_removeFile: function(num){
// issue if function is empty
},

_fileRender: function(){
var files = this.state.fileDetails.map( function(f, x) {
return(
<div key={x}>
<div className="">
<button onClick={this._removeFile.bind(this, x)}>Remove</button>
</div>
</div>
)
}.bind(this));
return(<div>{files}</div>)
},

render: function(){
return(<div>{this._fileRender()}</div>)
}

...


So when I click the remove button, the form submits. Why? That button passes data to
_removeFile()
. Regardless if that function's empty or not, it still submits.
e.preventDefault()
does nothing. My knowledge at this stage is limited so excuse the silly mistake, if any.

Worst case is to put
Component A
's submit button into an
onClick()
.

Answer

Any button will submit its parent form. This is what buttons do :)

If you need a button but want to prevent the default action you need to use event.preventDefault().

Since you prepopulate an argument to the function using .bind, the event object will be passed as the second argument:

 _removeFile: function(num, e){
     // do stuff with num
     e.preventDefault();
  },

working demo: http://jsfiddle.net/69z2wepo/47187/