Form submitts independently on button type in React

316 Views Asked by At

I have a simple code:

kill = e => {
// do the killing
}

save = e => {
  e.preventDefault()
  console.info(e.currentTarget)
}

render(){
  return <form onSubmit={this.save}>
    <button key={new Date().getTime()} onDoubleClick={this.kill}>Delete</button>}
    <button type="submit" key={new Date().getTime() + 100}>Save</button>
  </form>
}

If I click the Delete Button, the form gets submitted -> I see it in the console.

Double click works, but prior to that the save() method is invoked.

I found this bug https://github.com/facebook/react/issues/8554, and tried adding the unique key to each button, but nothing changes.

What am I missing?

2

There are 2 best solutions below

0
On BEST ANSWER

Try giving type="button" to the button that you don't want to submit.


The default behavior of the button. Possible values are:

submit: The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with a , or if the attribute is an empty or invalid value.

reset: The button resets all the controls to their initial values, like . (This behavior tends to annoy users.)

button: The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the element's events, which are triggered when the events occur.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

0
On

I think it's related to this: Can I make a <button> not submit a form?

Set <button type="button" [..] on the button should not submit the form.