Sushant Rajbanshi
Sushant Rajbanshi

Reputation: 2010

How to isolate handleSubmit() functions in React Hooks Form when the forms are nested such that they don't trigger each other?

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();
                        }

                      }
                    }}
                  >

Upvotes: 1

Views: 861

Answers (1)

Elio Rahi
Elio Rahi

Reputation: 164

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();
      }
    }

Upvotes: 1

Related Questions