Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Preventing Form Submission

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>&nbsp;   </p> </Form> 

What am I missing?

like image 417
Some User Avatar asked Oct 01 '16 18:10

Some User


People also ask

How Stop default form submit in react JS?

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.

What is the purpose of event preventDefault () in form submit handler in React?

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.

How do you prevent form submit on Enter in JavaScript?

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.

How do you refresh form after submit in React?

import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!


1 Answers

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

like image 183
eddywashere Avatar answered Oct 07 '22 02:10

eddywashere