// Look here we pass the args in the onClick
<Button color="primary" onClick={e => this.onTestClick(e)}>primary</Button>
Second one we pass it into argument and we did right in the onClick
onTestClick() {
alert('here');
}
// Here we did right inside the onClick, but this is the best way
<Button color="primary" onClick={e => (e.preventDefault(), this.onTestClick())}>primary</Button>
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.
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
}
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.
There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.
To stop the actual submission just include event in your function and an event.preventDefault(); to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.