Dave
Dave

Reputation: 168

React - Form submit fires onSubmit attached to parent of the form

I am wondering if someone can explain this behavior to me. I have a React component made up of a Form (React Bootstrap) wrapped in a Modal (React Bootstrap). I accidentally attached the onSubmit to the surrounding Modal, and that function gets fired when the form is submitted. I did not expect the function to run, but expected the form action to happen (a Wufoo URL). Can someone tell me why the function runs? Is it a React thing? Native form behavior? A little of both?

Example (dumbed down and removed React Bootstrap): JSFiddle

const MyForm = () => {

  const submitForm = (ev) => {
    ev.preventDefault();
    alert('submit');
  }

  return (
    <div onSubmit={submitForm}>
      <form>
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}

ReactDOM.render(<MyForm />, document.getElementById('root'));

Upvotes: 0

Views: 555

Answers (2)

imjared
imjared

Reputation: 20564

The onSubmit that's typically caught by the form's submit handler is just bubbling up through the DOM.

If you attach a e.stopPropagation to the <form> element, you'll see that submitForm is no longer called.

Upvotes: 1

HolyMoly
HolyMoly

Reputation: 2080

in JS events can bubble from an inner element to an outer one. i attached a link in the comment below your question ;)

Upvotes: 1

Related Questions