Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
  );
}
like image 354
Viktor Kireev Avatar asked Aug 20 '26 01:08

Viktor Kireev


1 Answers

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

like image 187
jarraga Avatar answered Aug 21 '26 14:08

jarraga