Reputation: 3851
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.
Upvotes: 17
Views: 32868
Reputation: 38817
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.
Upvotes: 33
Reputation: 760
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.
Upvotes: 1
Reputation: 1141
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>
Upvotes: 1