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.
To submit a form using the Enter key in React: Add a button element with type set to submit . Add an onSubmit prop that points to a submit handler function. Every time the user presses Enter, the handle submit function will be invoked.
To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.
To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted.
React invokes onSubmit() handler when the form is submitted, i.e. the user clicks Submit button.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With