How to submit a form by in a React Material UI dialog?

Sometimes, we want to submit a form by in a React Material UI dialog.

In this article, we’ll look at how to submit a form by in a React Material UI dialog.

How to submit a form by in a React Material UI dialog?

To submit a form by in a React Material UI dialog, we set the onSubmit prop to a function that calls e.preventDefault.

For instance, we write:

import * as React from "react";
import Dialog from "@material-ui/core/Dialog";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
import Box from "@material-ui/core/Box";

const useStyles = makeStyles((theme) => ({
  paper: {
    padding: "10px"
  }
}));

export default function App() {
  const classes = useStyles();
  const [open, setOpen] = React.useState(false);

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <button type="button" onClick={handleOpen}>
        Open Modal
      </button>
      <Dialog open={open}>
        <Box className={classes.paper}>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              handleClose();
            }}
          >
            <div>
              <TextField name="email" hintText="Email" />
            </div>
            <div>
              <TextField name="pwd" type="password" hintText="Password" />
            </div>
            <div>
              <button type="submit">Submit</button>
            </div>
          </form>
        </Box>
      </Dialog>
    </div>
  );
}

We add a Dialog with the open prop set to open state so that we make sure that the dialog is open only when open is true.

In the Dialog, we add the form element with the TextFields to add the inputs.

Then we add a button with type set to submit to run the function we set as the value of the onSubmit prop.

In the function, we call e.preventDefault to prevent the default server-side submission behavior.

And we call handleClose to set open to false to close the dialog box.

Conclusion

To submit a form by in a React Material UI dialog, we set the onSubmit prop to a function that calls e.preventDefault.