Form inside a material-ui Dialog is not submitting on Enter

Viewed 3103

I have a modal dialog with two buttons, one of which should work as a submit button. I'd like Enter to trigger the submit as well.

Here's my code for this component:

import React, { FormEvent } from 'react';
import { Button, Dialog, DialogActions, DialogContent, DialogContentText } from '@material-ui/core';

interface Props {
  close: () => void;
  onSubmit: () => void;
}

export default (props: Props) => {
  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    props.onSubmit();
    props.close();
  };

  return (
    <Dialog open onClose={props.close}>
      <form onSubmit={handleSubmit}>
        <DialogContent>
          <DialogContentText>
            You are about to submit the text. Are you sure you are done?
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button type="button" color="primary" variant="outlined" size="small">No, there is more to do</Button>
          <Button type="submit" color="primary" variant="contained" size="small">Yes, I&apos;m done here</Button>
        </DialogActions>
      </form>
    </Dialog>
  );
};

Clicking on a button works, Enter does not. I tried to put the form inside DialogActions — same result.

2 Answers

You can listen to the keyup event and tell the Dialog to submit and close if e.keyCode is 13 (which is the key code for Enter)

<Dialog
  onKeyUp={(e) => {
    const ENTER = 13;
    console.log(e.keyCode)

    if (e.keyCode === ENTER) {
      props.onSubmit();
      props.onClose();
    }
  }}
>
  {...}
</Dialog>

EDIT: if you hit Enter, onsubmit event will fire when the inputs or the submit button is in focused. You can add autofocus to the submit Button so when the Dialog is opened the Button will be focused by default. The user can then close the dialog by pressing Enter while the button is in focused

<Button
  autoFocus
  type="submit"
>

Live Demo

Edit 64498415/form-inside-a-material-ui-dialog-is-not-submitting-on-enter

Update 2022

keyCode is being depreciated.

use:

e.key

example:

if (e.key === 'Enter') {...}
Related