I am using React Hook Form for forms in my Next JS App. I have two forms FormA
& FormB
components. But the issue is whenever I execute the handleSubmit()
function for child FormB
, the handleSubmit()
function for parent FormA
also gets executed.
<FormA onSubmit(handleSubmit(submitFunctionA)>
............
<FormB onSubmit(handleSubmit(submitFunctionB))>
</FormB>
............
</FormA>
After applying suggestions from comments. My issue is fixed as shown below.
<form
onSubmit={(event) => {
//Child Form's onSubmit function here//
handleSubmit(onSubmit)(event);
if (event) {
if (typeof event.preventDefault === "function") {
event.preventDefault();
}
if (typeof event.stopPropagation === "function") {
event.stopPropagation();
}
}
}}
>
CodePudding user response:
Events get propagated up the tree to their parents, so this behaviour is normal. In order to stop the propagation, try adding this to your child handleSubmit:
if (event) {
if (typeof event.preventDefault === 'function') {
event.preventDefault();
}
if (typeof event.stopPropagation === 'function') {
event.stopPropagation();
}
}