I understand that without "type" attributes are submitted inside "form" tag. (this question)
One of the third-party react components I use has a button that doesn't have a type attribute, which causes it to be submitted unconditionally.
Is there a way to stop submitting a form if there is such a button in a third party component?
This code is just an example:
import React from "react";
import {SamethingComponent} from "samething-package";
export const MyComponent = () => {
const handleSubmit = (e) => {
// doSomething.
}
return (
<>
<form onSubmit={handleSubmit}>
{/* Component containing a button with no type attribute */}
<SamethingComponent/>
{/* This is needed as a normal submit button. */}
<button type="submit">Submit!</button>
</form>
</>
);
};
The default type for a <button> is submit. Setting type='button' should prevent it from submitting when clicked and turn it into a regular button.
Use onSubmit of the parent form.
<form onsubmit='event.preventDefault()'>
<button>Click me with impunity</button>
</form>
HTML:
<form id="form">
<input type="text"/>
<button>Submit</button>
</form>
JS:
const form = document.getElementById("form")
form.addEventListener('submit', event => {
event.preventDefault()
})
You can prevent all form submission in the form element by calling preventDefault on event object.