Programming

How to submit a form using Enter key in reactjs

27 September 2026 · 6 min read

How to submit a form using Enter key in reactjs

Building interactive web applications with React.js often involves forms, which are crucial for user input. A common expectation from users is the ability to submit a form simply by pressing the Enter key while typing in an input field. While this behavior is native to standard HTML forms, integrating it seamlessly into a React component requires understanding how React handles events and the browser’s default actions. This guide will walk you through the most effective and robust methods to ensure your users can easily submit a form using the Enter key in React.js, enhancing both user experience and the overall accessibility of your application. We’ll explore best practices, common pitfalls, and provide clear code examples to help you implement this functionality correctly.

Understanding Default Browser Behavior and React Forms

Before diving into React-specific implementations, it’s essential to understand how web browsers handle form submissions by default. In a standard HTML setup, if you have an <input type="text"> field inside an <form> element, pressing the Enter key while the input is focused will automatically trigger a submission of that form. This behavior occurs even if there isn’t an explicit submit button, though a submit button (<button type="submit"> or <input type="submit">) is usually present and recommended for accessibility.

When you’re working with React, you’re essentially building a single-page application where JavaScript controls the rendering and interaction. While React uses synthetic events that wrap native browser events, the underlying DOM behavior for forms largely remains. The key difference lies in how you “intercept” or handle these events within your React components. For instance, if you don’t explicitly prevent the default form submission behavior, the browser might perform a full page reload, which is usually undesirable in a React application. This is where React form handling comes into play, requiring developers to manage the submission process manually using event listeners React provides.

The most crucial aspect to remember is that the Enter key submission relies on the presence of a proper HTML <form> tag. Simply having a collection of input fields without wrapping them in a <form> element will prevent the browser’s default Enter key submission behavior from firing. This fundamental understanding is the first step towards correctly implementing Enter key submission in your React applications, ensuring a smoother user experience and avoiding unexpected page reloads.

Implementing Robust Form Submission with onSubmit

The recommended and most robust method to handle form submission, including via the Enter key, in React is by attaching an onSubmit event handler directly to the <form> element. When a user presses Enter inside any input field within that form, or clicks a type="submit" button, the browser will trigger the onSubmit event on the form. This approach centralizes your form submission logic and is generally considered the best practice for React form handling.

To submit a form using the Enter key in React.js, attach an onSubmit event handler to the <form> tag. Inside this handler, call event.preventDefault() to stop the browser’s default page reload behavior, then execute your custom submission logic, such as sending data to an API or updating component state. This method ensures that pressing Enter in any input field within the form will correctly trigger your designated submission function.

Here’s a practical example of how to implement this:

import React, { useState } from 'react'; function MyForm() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = (event) => { event.preventDefault(); // Prevents the default form submission (page reload) console.log('Form submitted!'); console.log('Username:', username); console.log('Password:', password); // Here you would typically send data to an API or perform other actions alert(Submitting: ${username} / ${password}); setUsername(''); // Clear form fields setPassword(''); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="username">Username:</label> <input type="text" id="username" value={username} onChange={(e) => setUsername(e.target.value)} aria-label="Enter your username" /> </div> <div> <label htmlFor="password">Password:</label> <input type="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} aria-label="Enter your password" /> </div> <button type="submit">Login</button> </form> ); } export default MyForm; 

In this code, the handleSubmit function is called whenever the form is submitted. The crucial event.preventDefault() line stops the browser from reloading the page, allowing your React application to manage the submission dynamically. This is the most reliable way to ensure keyboard events React handles for form submission are consistent and predictable across different browsers. For more detailed insights into general web form best practices, you can refer to resources like MDN Web Docs on the HTML Form element.

Handling onKeyDown for Specific Input Fields (When onSubmit Isn’t Enough)

While the onSubmit method on the <form> element is generally preferred, there are specific scenarios where you might need to handle the Enter key press on an individual input field. This is common for components that function more like a search bar or a single-line chat input, where the input itself acts as the “form” and isn’t necessarily wrapped in a traditional <form> tag. In these cases, you can use the onKeyDown event listener directly on the input element.

When using onKeyDown, you need to explicitly check if the pressed key was the Enter key. This is typically done by checking event.key === 'Enter' or event.keyCode === 13 (though event.key is generally preferred for modern browsers and readability). Similar to onSubmit, you’ll still need to call event.preventDefault() if there’s any default Question & Answer :

Here is my form and the onClick method. I would like to execute this method when the Enter button of keyboard is pressed. How ?

N.B: No jquery is appreciated.

comment: function (e) { e.preventDefault(); this.props.comment({ comment: this.refs.text.getDOMNode().value, userPostId:this.refs.userPostId.getDOMNode().value, }) }, <form className="commentForm"> <textarea rows="2" cols="110" placeholder="****Comment Here****" ref="text" /><br /> <input type="text" placeholder="userPostId" ref="userPostId" /> <br /> <button type="button" className="btn btn-success" onClick={this.comment}>Comment</button> </form> 

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={onFormSubmit}>. This should catch clicking the button and pressing the return key.

const onFormSubmit = e => { e.preventDefault(); // send state to server with e.g. `window.fetch` } ... <form onSubmit={onFormSubmit}> ... <button type="submit">Submit</button> </form> 

Full example without any silly form libraries:

function LoginForm() { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [submitting, setSubmitting] = useState(false) const [formError, setFormError] = useState('') const onFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => { try { e.preventDefault(); setFormError('') setSubmitting(true) await fetch(/*POST email + password*/) } catch (err: any) { console.error(err) setFormError(err.toString()) } finally { setSubmitting(false) } } return ( <form onSubmit={onFormSubmit}> <input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.currentTarget.value)} required /> <input type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.currentTarget.value)} required /> {Boolean(formError) && <div className="form-error">{formError}</div> } <button type="submit" disabled={submitting}>Login</button> </form> ) } 

P.S. Remember that any buttons in your form which should not submit the form should explicitly have type="button".