React - Preventing Form Submission
I think it's first worth noting that without javascript (plain html), the form
element submits when clicking either the <input type="submit" value="submit form">
or <button>submits form too</button>
. In javascript you can prevent that by using an event handler and calling e.preventDefault()
on button click, or form submit. e
is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit
, and the other on the button via onClick
.
Example: http://jsbin.com/vowuley/edit?html,js,console,output
No JS needed really ...
Just add a type
attribute to the button with a value of button
<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>
By default, button elements are of the type "submit" which causes them to submit their enclosing form element (if any). Changing the type
to "button" prevents that.
preventDefault is what you're looking for. To just block the button from submitting
<Button onClick={this.onClickButton} ...
code
onClickButton (event) {
event.preventDefault();
}
If you have a form which you want to handle in a custom way you can capture a higher level event onSubmit which will also stop that button from submitting.
<form onSubmit={this.onSubmit}>
and above in code
onSubmit (event) {
event.preventDefault();
// custom form handling here
}