Sometimes, we want to submit the form that is inside a dialog using React Material UI.
In this article, we’ll look at how to submit the form that is inside a dialog using React Material UI.
How to submit the form that is inside a dialog using React Material UI?
To submit the form that is inside a dialog using React Material UI, we can put a form element inside the dialog and add a input with type submit inside the form.
For instance, we write:
import React from "react";
import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import DialogContent from "@material-ui/core/DialogContent";
import DialogActions from "@material-ui/core/DialogActions";
import TextField from "@material-ui/core/TextField";
export default function App() {
const [staffNumber, setStaffNumber] = React.useState();
const [open, setOpen] = React.useState(false);
const handleCreate = (e) => {
e.preventDefault();
console.log(staffNumber);
setStaffNumber("");
setOpen(false);
};
return (
<div>
<Button onClick={() => setOpen(true)}>open</Button>
<Dialog title="Dialog" open={open}>
<DialogContent>
<form onSubmit={handleCreate} id="myform">
<TextField
value={staffNumber}
onChange={(e) => setStaffNumber(e.target.value)}
/>
</form>
</DialogContent>
<DialogActions>
<Button variant="contained" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button variant="contained" type="submit" form="myform">
Submit
</Button>
</DialogActions>
</Dialog>
</div>
);
}
We add the Dialog
component to add a dialog box.
Then we add the DialogContent
component to add the dialog content pane.
Next, we add the DialogActions
component to add the dialog actions pane.
We add the form element in the DialogContent
component and we add a Button
with type
set to submit
and the the form
attribute set to myForm
to let us submit the form when we click on it. This works since the form’s id
attribute matches the form
attribute of the Button
.
Then we set the onSubmit
prop of the form to handleCreate
to run it when we click on Submit.
In handleCreate
, we call e.preventDefault
to stop server side submission.
And we call setOpen
with false
to set open
to false
.
Since we set the open
prop of the Dialog
to open
, the dialog would close when open
is false
.
Conclusion
To submit the form that is inside a dialog using React Material UI, we can put a form element inside the dialog and add a input with type submit inside the form.