I have a form inside a form, The <form/>
inside form is rendered as Material UI dialog and rendered to DOM in a different portal.
/* SPDX-FileCopyrightText: 2021 @koistya */
/* SPDX-License-Identifier: MIT */
import * as React from "react";
import {
Button,
Dialog,
DialogContent,
Stack,
TextField,
Typography,
CssBaseline,
Container,
} from "@mui/material";
import { Combobox } from "./Combobox";
import { AppToolbar, Toolbar } from "./AppToolbar";
import { ThemeProvider } from "./ThemeProvider";
/**
* The top-level (root) React component.
*
* @see https://reactjs.org/
* @see https://mui.com/core/
*/
export function App(): JSX.Element {
const [open, setOpen] = React.useState(false);
return (
<ThemeProvider>
<CssBaseline />
<Container sx={{ my: 2 }}>
<Button
variant="contained"
sx={{ mb: 3 }}
onClick={() => setOpen(true)}
>
Open Dialog
</Button>
<form
onSubmit={(evt) => {
evt.preventDefault();
alert("Form outside dialog");
}}
>
<Typography variant="h6" component="h1" sx={{ mb: 2 }}>
Form outside dialog
</Typography>
<Stack spacing={2}>
{/* #region DIALOG */}
<Dialog open={open} onClose={() => setOpen(false)}>
<DialogContent>
<form
onSubmit={(evt) => {
evt.preventDefault();
alert("Form inside dialog");
}}
>
<Typography variant="h6" component="h1" sx={{ mb: 2 }}>
Form inside dialog
</Typography>
<Stack spacing={2}>
<TextField placeholder="name inside dialog" />
<TextField placeholder="email inside dialog" />
<Button type="submit" variant="contained">
Submit
</Button>
</Stack>
</form>
</DialogContent>
</Dialog>
{/* #endregion DIALOG */}
<TextField placeholder="name outside dialog" />
<TextField placeholder="email outside dialog" />
<Button type="submit" variant="contained">
Submit
</Button>
</Stack>
</form>
</Container>
</ThemeProvider>
);
}
When I open the dialog and submit the form inside the dialog. The form outside dialog will triggered. Is there a way to prevent this?
Visit this link for code reproduction
1 is root 2 is dialog portal
CodePudding user response:
You can add the stopPropagation event in your submit of your modal
<form
onSubmit={(evt) => {
evt.preventDefault();
evt.stopPropagation();
alert("Form inside dialog");
}}
>
CodePudding user response:
You can use event.stopPropagation
inside the inner form submit (dialog submit):
onSubmit={(evt) => {
evt.preventDefault();
evt.stopPropagation(); // <----
alert("Form inside dialog");
}}
Another solution would be to put the dialog outside the outer form. Both solutions are valid.