17

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.

3 Answers 3

33

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Now it's working. I had to use event.preventDefault() in handleSubmit to stop reloading page. Thanks for your help :)
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>

Comments

1

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.

1 Comment

Chances are, your <Button> is not inside a <form>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.