I've been experimenting with React. In my experiement, I'm using the Reactstrap framework.When I click a button, I've noticed that the HTML form submits. Is there a way to prevent form submission when a button is clicked?
I've recreated my issue here. My form is pretty basic and looks like this:
<Form> <h3>Buttons</h3> <p> <Button color="primary" onClick={this.onTestClick}>primary</Button> </p> </Form>
What am I missing?
Use the preventDefault() method on the event object to prevent form submission in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form.
Use preventDefault() event method to Prevent form submission on the “Enter” key pressed in JavaScript. Enter key keycode is 13, so you can check in if statement.
import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With