Viktor Kireev
Viktor Kireev

Reputation: 1250

Two forms on the same level are submitted in react app

I have react app with with complex component layout with multiple forms. I know that placing one form inside another is not allowed. But I have a component which renders a form and must be placed inside my form. To prevent forms be rendered one inside another I use react portal.

But when I try to submit form rendered with portal, first form is also submitted that is unexpected. Looks like I miss something important.

How to prevent first form submit when submitting the second?

Thank you

Simplified example is here

import { createPortal } from "react-dom";

const Portal = ({ children, elm }) => createPortal(children, elm);

export default function App() {
  return (
    <div className="App">
      <form
        onSubmit={(e) => {
          e.preventDefault();
          alert("submit 1");
        }}
      >
        First form <input type="text" value="1" />
        <Portal elm={document.querySelector("body")}>
          Second form{" "}
          <form
            onSubmit={(e) => {
              e.preventDefault();
              alert("submit 2");
            }}
          >
            <input type="text" value="2" />
            <input type="submit" value="submit 2" />
          </form>
        </Portal>
      </form>
    </div>
  );
}

Upvotes: 3

Views: 1091

Answers (1)

jarraga
jarraga

Reputation: 437

I had the same problem, as @EisaRezaei said in the first comment, using e.stopPropagation() in the form inside the portal, and submit type buttons, everything worked fine

Upvotes: 2

Related Questions