Handling Form Events in React JS
Handling Form Events is an important concept in React JS that allows developers to manage user interactions with forms. It includes handling text input, email fields, passwords, checkboxes, radio buttons, dropdowns, form submissions, validation, and reset actions. React event handlers work with component state to create interactive and dynamic forms.
Learn more through JustAcademy React JS Training or Register for React JS Course Demo.
1. What Is Form Event Handling in React?
Form event handling in React means responding to user actions performed on form elements. These actions include typing into an input, selecting an option, checking a checkbox, submitting a form, or resetting its values.
React uses event handler functions to respond to these actions and update the component state or perform other tasks.
Example:
function App() {
function handleChange(event) {
console.log(event.target.value);
}
return (
<input
type="text"
onChange={handleChange}
placeholder="Enter your name"
/>
);
}
export default App;
In this example, the onChange event handler runs when the input value changes and logs the current value to the console.
2. Why Is Form Event Handling Important?
- User interaction: Responds to user actions in forms.
- Data collection: Collects information such as names, emails, and phone numbers.
- Form validation: Checks whether user input meets specified requirements.
- State management: Keeps input values synchronized with React state.
- Submission handling: Processes form data when users submit a form.
- Error handling: Displays helpful messages when input is invalid.
- Better user experience: Provides immediate feedback and clear form behavior.
3. Common Form Events in React
| Event |
Purpose |
Example |
| onChange |
Responds when an input value changes. |
onChange={handleChange} |
| onSubmit |
Responds when a form is submitted. |
onSubmit={handleSubmit} |
| onFocus |
Runs when an element receives focus. |
onFocus={handleFocus} |
| onBlur |
Runs when an element loses focus. |
onBlur={handleBlur} |
| onInput |
Responds to immediate input changes. |
onInput={handleInput} |
| onReset |
Responds when a form is reset. |
onReset={handleReset} |
| onInvalid |
Responds when a form element fails native constraint validation. |
onInvalid={handleInvalid} |
| onKeyDown |
Responds when a key is pressed down. |
onKeyDown={handleKeyDown} |
Note: React's onChange handler for text inputs behaves similarly to the browser's input event and runs as the user changes the value.
4. Handling the onChange Event
The onChange event is commonly used to track changes in text fields, email inputs, passwords, textareas, and other form controls. The event object provides access to the element through event.target.
Example:
function NameForm() {
function handleChange(event) {
console.log("Entered name:", event.target.value);
}
return (
<div>
<label htmlFor="name">Name:</label>
<input
id="name"
type="text"
onChange={handleChange}
/>
</div>
);
}
export default NameForm;
Whenever the user types or edits the input, handleChange receives the event and reads the current value using event.target.value.
5. Handling Form Input with useState
The useState Hook allows a component to store and update form values. It is commonly used to create controlled components, where React state determines the value displayed in the form control.
Example:
import { useState } from "react";
function NameForm() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<label htmlFor="name">Name:</label>
<input
id="name"
type="text"
value={name}
onChange={handleChange}
/>
<p>Your name: {name}</p>
</div>
);
}
export default NameForm;
Explanation:
- useState initializes name as an empty string.
- value={name} connects the input value to React state.
- onChange={handleChange} responds to user input.
- setName(event.target.value) updates the state.
- The paragraph displays the latest name as the component re-renders.
6. Handling the onSubmit Event
The onSubmit event runs when a form is submitted, such as when a user clicks a submit button or presses Enter in an appropriate input. In React, event.preventDefault() is commonly used to prevent the browser's default form submission and page reload when handling the submission in JavaScript.
Example:
function ContactForm() {
function handleSubmit(event) {
event.preventDefault();
alert("Form submitted successfully!");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input id="name" type="text" required />
<button type="submit">Submit</button>
</form>
);
}
export default ContactForm;
Explanation:
- The form uses the onSubmit event handler.
- event.preventDefault() prevents the default browser submission behavior.
- The handler can validate the form or process the data.
- The required attribute enables basic browser validation.
Important: Preventing the default behavior does not automatically save data to a database. You must implement the appropriate API request or data-processing logic.
7. Handling Multiple Form Fields
A form can contain multiple fields, such as name, email, and password. One common approach is to store all field values in a single state object and update the relevant property when a field changes.
Example:
import { useState } from "react";
function RegistrationForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
password: ""
});
function handleChange(event) {
const { name, value } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: value
}));
}
function handleSubmit(event) {
event.preventDefault();
console.log(formData);
}
return (
<form onSubmit={handleSubmit}>
<input
name="name"
placeholder="Enter your name"
value={formData.name}
onChange={handleChange}
required
/>
<input
name="email"
type="email"
placeholder="Enter your email"
value={formData.email}
onChange={handleChange}
required
/>
<input
name="password"
type="password"
placeholder="Enter your password"
value={formData.password}
onChange={handleChange}
required
/>
<button type="submit">Register</button>
</form>
);
}
export default RegistrationForm;
Explanation: The name attribute identifies the field being updated. The spread operator preserves the other field values while updating the changed property.
8. Controlled Components in React
A controlled component is a form element whose value is controlled by React state. The input receives a value prop and an event handler updates that state when the user changes the input.
Example:
import { useState } from "react";
function ControlledInput() {
const [email, setEmail] = useState("");
return (
<div>
<input
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<p>Email: {email}</p>
</div>
);
}
export default ControlledInput;
Advantages:
- Provides direct access to input values through state.
- Makes validation and conditional UI updates easier.
- Supports resetting fields through state updates.
- Helps keep the displayed input value synchronized with application data.
Important: A controlled text input should consistently receive a string value, and a controlled checkbox should use a boolean checked value.
9. Uncontrolled Components in React
An uncontrolled component stores its current value in the DOM rather than keeping it synchronized with React state on every change. You can read its value through a ref or use FormData when submitting a form.
Example using FormData:
function SearchForm() {
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const query = formData.get("query");
console.log("Search query:", query);
}
return (
<form onSubmit={handleSubmit}>
<input name="query" placeholder="Search..." />
<button type="submit">Search</button>
</form>
);
}
export default SearchForm;
In this example, FormData reads the field value when the form is submitted. The input does not need a React state value or an onChange handler.
10. Handling Checkbox Events
Checkboxes are commonly used for preferences, consent, and multiple selections. In React, the checked property indicates whether a checkbox is selected.
Example:
import { useState } from "react";
function TermsForm() {
const [accepted, setAccepted] = useState(false);
return (
<div>
<label>
<input
type="checkbox"
checked={accepted}
onChange={(event) => setAccepted(event.target.checked)}
/>
I accept the terms and conditions
</label>
<p>Accepted: {accepted ? "Yes" : "No"}</p>
</div>
);
}
export default TermsForm;
Use event.target.checked for checkbox values rather than event.target.value.
11. Handling Radio Button Events
Radio buttons allow users to select one option from a group. Radio inputs with the same name are grouped together, and their selected value can be stored in React state.
Example:
import { useState } from "react";
function GenderForm() {
const [gender, setGender] = useState("");
return (
<div>
<label>
<input
type="radio"
name="gender"
value="Male"
checked={gender === "Male"}
onChange={(event) => setGender(event.target.value)}
/>
Male
</label>
<label>
<input
type="radio"
name="gender"
value="Female"
checked={gender === "Female"}
onChange={(event) => setGender(event.target.value)}
/>
Female
</label>
<p>Selected: {gender || "None"}</p>
</div>
);
}
export default GenderForm;
12. Handling Dropdown and Select Events
The select element allows users to choose an option from a dropdown list. Its selected value can be managed through state and the onChange event.
Example:
import { useState } from "react";
function CourseForm() {
const [course, setCourse] = useState("");
return (
<div>
<label htmlFor="course">Choose a course:</label>
<select
id="course"
value={course}
onChange={(event) => setCourse(event.target.value)}
>
<option value="">Select a course</option>
<option value="React JS">React JS</option>
<option value="JavaScript">JavaScript</option>
<option value="Node.js">Node.js</option>
</select>
<p>Selected course: {course || "None"}</p>
</div>
);
}
export default CourseForm;
13. Handling Textarea Events
The textarea element is used to collect longer text, such as comments, feedback, and descriptions. In React, a controlled textarea uses value and onChange.
Example:
import { useState } from "react";
function FeedbackForm() {
const [feedback, setFeedback] = useState("");
return (
<div>
<textarea
value={feedback}
onChange={(event) => setFeedback(event.target.value)}
placeholder="Write your feedback"
rows={4}
/>
<p>Characters: {feedback.length}</p>
</div>
);
}
export default FeedbackForm;
14. Handling Focus and Blur Events
The onFocus event occurs when an input receives focus, while onBlur occurs when it loses focus. These events can be used to show instructions or validate a field after the user finishes editing it.
Example:
function EmailInput() {
function handleFocus() {
console.log("Email field focused");
}
function handleBlur() {
console.log("Email field lost focus");
}
return (
<input
type="email"
placeholder="Enter email"
onFocus={handleFocus}
onBlur={handleBlur}
/>
);
}
export default EmailInput;
15. Preventing Default Form Submission
By default, submitting a standard HTML form can send the form data to a URL and reload the page. In React, event.preventDefault() is commonly used when the submission must be handled by JavaScript instead.
Example:
function LoginForm() {
function handleSubmit(event) {
event.preventDefault();
console.log("Custom form submission");
}
return (
<form onSubmit={handleSubmit}>
<input name="username" required />
<button type="submit">Login</button>
</form>
);
}
export default LoginForm;
Remember: event.preventDefault() prevents the default browser action. It does not validate credentials, authenticate a user, or submit data to a server automatically.
16. Form Validation in React
Form validation checks whether the information entered by the user meets the required rules before processing the submission. Validation can use built-in HTML attributes, custom JavaScript checks, or a combination of both.
Common Validation Rules
- Required fields must not be empty.
- Email addresses should follow an acceptable email format.
- Password fields should meet the application's security requirements.
- Phone numbers should be checked against the expected format.
- Passwords and confirmation passwords should match when required.
Example:
import { useState } from "react";
function EmailForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
function handleSubmit(event) {
event.preventDefault();
if (!email.trim()) {
setError("Email is required.");
return;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
setError("Please enter a valid email address.");
return;
}
setError("");
alert("Email submitted successfully!");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
{error && <p role="alert">{error}</p>}
<button type="submit">Submit</button>
</form>
);
}
export default EmailForm;
This example validates whether the email is empty or matches a basic email pattern. Real applications should also validate data on the server because client-side validation alone is not a security measure.
17. Handling Form Reset Events
The onReset event is triggered when a form reset is requested. For controlled components, update React state as well so the displayed fields return to their initial values.
Example:
import { useState } from "react";
function ResetForm() {
const [name, setName] = useState("");
function handleReset() {
setName("");
}
return (
<form onReset={handleReset}>
<input
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Enter name"
/>
<button type="reset">Reset</button>
</form>
);
}
export default ResetForm;
18. Handling Keyboard Events in Forms
Keyboard events allow a component to respond to key presses. They can be used for shortcuts or special input interactions, but standard form submission should generally use the form's onSubmit event.
Example:
function SearchInput() {
function handleKeyDown(event) {
if (event.key === "Escape") {
event.currentTarget.value = "";
}
}
return (
<input
type="text"
placeholder="Search..."
onKeyDown={handleKeyDown}
/>
);
}
export default SearchInput;
For a controlled input, update React state instead of changing the DOM value directly. This keeps the displayed value synchronized with the state.
19. Complete Practical Example: React Registration Form
This example combines input handling, state management, form submission, basic validation, and success messages in a single component.
RegistrationForm.jsx
import { useState } from "react";
function RegistrationForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
course: ""
});
const [message, setMessage] = useState("");
function handleChange(event) {
const { name, value } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: value
}));
setMessage("");
}
function handleSubmit(event) {
event.preventDefault();
if (!formData.name.trim() ||
!formData.email.trim() ||
!formData.course) {
setMessage("Please complete all fields.");
return;
}
setMessage(
`Thank you, ${formData.name}! Your selected course is ${formData.course}.`
);
}
function handleReset() {
setFormData({ name: "", email: "", course: "" });
setMessage("");
}
return (
<div>
<h2>Course Registration</h2>
<form onSubmit={handleSubmit} onReset={handleReset}>
<label htmlFor="name">Full Name:</label>
<input
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
<label htmlFor="email">Email:</label>
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
required
/>
<label htmlFor="course">Select Course:</label>
<select
id="course"
name="course"
value={formData.course}
onChange={handleChange}
required
>
<option value="">Choose a course</option>
<option value="React JS">React JS</option>
<option value="JavaScript">JavaScript</option>
<option value="Node.js">Node.js</option>
</select>
<button type="submit">Register</button>
<button type="reset">Reset</button>
</form>
{message && <p role="status">{message}</p>}
</div>
);
}
export default RegistrationForm;
How It Works
- useState stores the registration fields and feedback message.
- handleChange updates the relevant form field.
- handleSubmit prevents the default page reload and checks the required fields.
- handleReset clears the controlled values and message.
- The status message provides feedback after submission.
Note: This is a frontend demonstration. It does not send registration data to a backend or database.
20. Common Mistakes in Handling Form Events
- Forgetting event.preventDefault(): The browser may perform its default submission and reload the page.
- Using the wrong event property: Read text values with event.target.value and checkbox selection with event.target.checked.
- Not updating state: A controlled input needs an onChange handler that updates its state.
- Incorrect state updates: When updating an object, preserve other properties using the spread operator or another appropriate immutable update.
- Calling the handler immediately: Use onClick={handleClick}, not onClick={handleClick()}, when the function should run after a click.
- Missing name attributes: FormData uses field names to retrieve values.
- Ignoring validation: Validate input before processing it, and validate again on the server where appropriate.
- Direct DOM manipulation: Avoid changing controlled input values directly because the DOM can become inconsistent with React state.
- Using the wrong button type: Specify type="submit" for submission and type="button" for buttons that should not submit the form.
21. Best Practices for Handling Form Events
- Use controlled components when you need live access to field values.
- Use descriptive names for event handler functions, such as handleChange and handleSubmit.
- Keep related form values organized in state.
- Use label elements and connect them to inputs with htmlFor and id.
- Use appropriate input types, such as email, password, and number, where applicable.
- Display clear and accessible validation messages.
- Use event.preventDefault() when handling form submission with JavaScript.
- Disable submission when appropriate during asynchronous operations to prevent duplicate requests.
- Keep sensitive information out of console logs and error messages.
- Perform server-side validation before storing or trusting submitted data.
22. Difference Between onChange and onSubmit
| onChange |
onSubmit |
| Runs when a form control's value changes. |
Runs when a form is submitted. |
| Commonly used to update state. |
Commonly used to validate and process form data. |
| Can run many times while typing. |
Usually runs when the user submits the form. |
| Example: tracking a name input. |
Example: processing a registration form. |
23. Interview Questions and Answers
Q1. What is form event handling in React?
It is the process of responding to user actions on form elements using event handlers and, when needed, component state.
Q2. What is the purpose of onChange?
It responds when an input's value changes and is commonly used to update React state.
Q3. What is the purpose of onSubmit?
It handles form submission and can be used to validate or process the submitted data.
Q4. Why is event.preventDefault() used?
It prevents the browser's default action, such as the usual page reload associated with standard form submission.
Q5. What is a controlled component?
A controlled component is a form element whose displayed value or checked state is controlled by React state.
Q6. What is an uncontrolled component?
An uncontrolled component keeps its current value in the DOM, and its value can be read through a ref or FormData.
Q7. How do you handle multiple inputs using one function?
Give each field a name attribute, read name and value from event.target, and update the matching property in a state object.
Q8. How do you handle a checkbox?
Use the checked property and read event.target.checked to determine whether it is selected.
Q9. What is form validation?
Form validation checks whether the user's input meets required conditions before the application processes it.
Q10. Can React form handling save data to a database automatically?
No. A frontend form must connect to an appropriate backend or service to persist data, and the server should validate the submitted information.
24. Practice Exercises
- Create a login form with username and password fields.
- Create a registration form with name, email, phone, and course fields.
- Display the entered name below an input field using useState.
- Create a feedback form using a textarea and count the entered characters.
- Build a dropdown for selecting a course and display the selected option.
- Create a checkbox for accepting terms and conditions.
- Validate that an email field is not empty before submission.
- Build a form with submit and reset buttons.
- Display a success message after a valid form submission.
- Read form values using FormData without making every input controlled.
25. Quick Revision Checklist
- Understand React form events and event handler functions.
- Practice onChange and onSubmit.
- Understand event.target.value and event.target.checked.
- Learn to manage form values with useState.
- Understand controlled and uncontrolled components.
- Practice handling checkboxes, radio buttons, select elements, and textareas.
- Learn form validation and error messages.
- Understand event.preventDefault() and form reset behavior.
- Build a complete registration form.
26. Conclusion
Handling Form Events is an essential React JS skill for creating interactive forms and collecting user input. By understanding onChange, onSubmit, useState, controlled and uncontrolled components, validation, and reset behavior, developers can build reliable and user-friendly forms. Regular practice with login forms, registration forms, feedback forms, and search forms will strengthen your React development skills.
Continue learning through JustAcademy React JS Training and Register for React JS Course Demo.
Official React References