15

Here is my form in render method which is for user sign-in.

<form onSubmit={this.handleSubmit}>
  <Avatar className={classes.avatar}>
    <LockOutlinedIcon />
  </Avatar>
  <Typography component="h1" variant="h5">
    Sign in
  </Typography>

  <TextField variant="outlined" margin="normal" fullWidth id="email"
    label="Email Address" name="email" onChange={this.handleEmailChange}
  />
  <TextField variant="outlined" margin="normal" fullWidth
    name="password" onChange={this.handlePasswordChange}
  />
  {loginError && (
    <Typography component="p" className={classes.errorText}>
      Incorrect email or password.
    </Typography>
  )}

  <Button type="button" fullWidth variant="contained" color="primary"
    className={classes.submit} onClick={this.handleSubmit}
  >
    Sign In
  </Button>
</form>

And the following is my handle submit method.

handleSubmit = () => {
  const { dispatch } = this.props;
  const { email, password } = this.state;
  dispatch(loginUser(email, password));
};

How can I submit the form by pressing the Enter key? I am using the standard Material UI Button component.

David Harkness
  • 35,992
  • 10
  • 112
  • 134
Ali Rehman
  • 3,731
  • 4
  • 23
  • 28

3 Answers3

32

Try the following by making the button of type "submit" instead. This should enable form submit using the enter key:

<Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit}>
  Sign In
</Button>

Also with type "submit" you don't need onClick, because clicking a submit button triggers the form submit event by default.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • 4
    Now it's working. I had to use event.preventDefault() in handleSubmit to stop reloading page. Thanks for your help :) – Ali Rehman Nov 04 '19 at 20:11
1

You have to use type="submit" as for the button Ex:

    <Button 
        type="submit" 
        fullWidth 
        variant="contained"
        color="primary"
        className={classes.submit}
    >
        Sign In
    </Button>
Govinda Malavipathirana
  • 1,095
  • 2
  • 11
  • 29
0

Adding type=submit in Button did not work for me. You could try with this solution here. It uses a UseEffect hook which works in React.

L. Pier Roberto
  • 513
  • 1
  • 6
  • 20