Popular Searches
Popular Course Categories
Popular Courses

Handling Form Events

Handling Form Events

React Events and Conditional Rendering

Handling Form Events in React JS

Handling Form Events in React JS is the process of managing user interactions with form elements such as text fields, email inputs, passwords, checkboxes, radio buttons, dropdowns, and text areas. React provides event handlers like onChange, onSubmit, onFocus, onBlur, and onInvalid to respond to user actions, collect input values, validate information, and submit forms.

Form event handling is an essential part of building interactive applications such as login pages, registration forms, contact forms, search forms, feedback forms, and checkout pages.


1. What Are Form Events in React?

Form events are actions triggered when a user interacts with a form or one of its fields. React allows developers to attach event handlers to form elements using JSX attributes written in camelCase.

For example, when a user types into a text field, the onChange event can update the component's state. When the user submits a form, the onSubmit event can validate and process the entered information.

Common Form Events

Event Purpose Example Use
onChange Responds when an input value changes. Updating a username while typing.
onSubmit Handles form submission. Processing a registration form.
onFocus Runs when an element receives focus. Highlighting an active input field.
onBlur Runs when an element loses focus. Validating an email after the user leaves the field.
onInvalid Responds when a field fails browser constraint validation. Handling a missing required value.
onReset Handles a form reset event. Clearing a form's fields.
onInput Responds to user input changes. Reacting to text entry.

2. Why Is Form Event Handling Important?

  • Collects user information: Reads names, email addresses, passwords, and other field values.
  • Updates the interface: Displays entered information or changes the UI based on user input.
  • Validates data: Checks whether the submitted information meets application requirements.
  • Prevents unwanted page reloads: Allows React to handle submissions without the browser performing its default navigation.
  • Improves user experience: Provides helpful messages and immediate feedback.
  • Supports interactive applications: Makes login, registration, search, and contact forms functional.

3. Handling the onChange Event

The onChange event is commonly used to track changes in text inputs, email inputs, dropdowns, and text areas. In React, it fires when the user changes the field's value, such as while typing.

Example: Handling a Text Input

import { useState } from "react";

function UsernameForm() {
  const [username, setUsername] = useState("");

  function handleChange(event) {
    setUsername(event.target.value);
  }

  return (
    <div>
      <label htmlFor="username">Username:</label>
      <input
        id="username"
        type="text"
        value={username}
        onChange={handleChange}
      />
      <p>Entered username: {username}</p>
    </div>
  );
}

export default UsernameForm;

Explanation

  • useState("") creates a state variable with an empty initial value.
  • username stores the current input value.
  • setUsername() updates the state when the user types.
  • event.target.value retrieves the current value of the input element.
  • value={username} keeps the input synchronized with React state.
  • onChange={handleChange} connects the event handler to the input.

4. Handling the onSubmit Event

The onSubmit event runs when a form is submitted, usually by clicking a submit button or pressing Enter in a suitable field. It is used to validate the form, collect data, and start an operation such as sending information to a server.

By default, the browser may submit the form through its normal navigation behavior. Calling event.preventDefault() prevents that default behavior so the React handler can process the submission.

Example: Basic Form Submission

import { useState } from "react";

function LoginForm() {
  const [username, setUsername] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    alert("Welcome, " + username + "!");
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="username">Username:</label>
      <input
        id="username"
        type="text"
        value={username}
        onChange={(event) => setUsername(event.target.value)}
        required
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default LoginForm;

Explanation

  • The form uses onSubmit={handleSubmit} to process submission.
  • event.preventDefault() prevents the default browser form submission.
  • The input's onChange handler updates the username state.
  • The required attribute enables browser validation for an empty field.
  • The submit button triggers the form submission handler.

5. Understanding the Event Object

React passes an event object to an event handler. It provides information about the event and the element involved.

Property or Method Description
event.target The element where the event originated.
event.currentTarget The element whose handler is currently executing.
event.target.value The current value of a text input or select field.
event.target.checked Indicates whether a checkbox or radio input is checked.
event.preventDefault() Prevents the browser's default action for the event.
event.stopPropagation() Stops the event from propagating to ancestor handlers.

Example: Reading an Input Value

function handleChange(event) {
  console.log(event.target.value);
}

Whenever the user changes the input, the current value is printed in the browser console.


6. Controlled Components in React

A controlled component is a form element whose current value is managed by React state. The input receives its value through the value prop, and its onChange handler updates that state.

Example

import { useState } from "react";

function ControlledInput() {
  const [email, setEmail] = useState("");

  return (
    <div>
      <input
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        placeholder="Enter your email"
      />
      <p>Email: {email}</p>
    </div>
  );
}

export default ControlledInput;

Advantages of Controlled Components

  • React state always represents the current field value.
  • Form validation can run as the user types.
  • Fields can be cleared or updated programmatically.
  • Conditional UI can depend on input values.
  • Form data can be processed consistently before submission.

Important: A controlled text input needs an onChange handler that synchronously updates its state. Otherwise, the input may become effectively read-only. Initialize text values with strings such as "" rather than null or undefined.


7. Uncontrolled Components in React

An uncontrolled component stores its current value in the DOM rather than continuously controlling it through React state. You can provide an initial value using defaultValue and read the final values when submitting the form.

Example: Using FormData

function ContactForm() {
  function handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData(event.currentTarget);
    const name = formData.get("name");
    const email = formData.get("email");

    alert("Name: " + name + "\\nEmail: " + email);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" defaultValue="" placeholder="Your name" required />
      <input name="email" type="email" placeholder="Your email" required />
      <button type="submit">Send</button>
    </form>
  );
}

export default ContactForm;

How FormData Works

  • new FormData(event.currentTarget) collects the named form controls.
  • formData.get("name") retrieves the field named name.
  • Each field should have a meaningful name attribute.
  • This method is useful when you do not need React state to track every keystroke.

8. Handling Multiple Form Fields

Real-world forms commonly contain multiple fields. React can manage them using separate state variables or one state object.

Example: Registration Form with Multiple Fields

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("Submitted data:", formData);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        name="name"
        value={formData.name}
        onChange={handleChange}
        placeholder="Full name"
        required
      />
      <input
        name="email"
        type="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Email address"
        required
      />
      <input
        name="password"
        type="password"
        value={formData.password}
        onChange={handleChange}
        placeholder="Password"
        required
      />
      <button type="submit">Register</button>
    </form>
  );
}

export default RegistrationForm;

Explanation

  • The state object stores all three fields.
  • The name attribute identifies which field changed.
  • event.target.value retrieves the new value.
  • The spread operator ... preserves the other field values.
  • The computed property [name] updates the appropriate field.
  • The submit handler processes the complete form object.

9. Handling Checkbox Events

Checkboxes are used for terms and conditions, newsletter subscriptions, preferences, and other true-or-false choices. For a controlled checkbox, use the checked prop and read event.target.checked.

Example

import { useState } from "react";

function TermsForm() {
  const [accepted, setAccepted] = useState(false);

  function handleSubmit(event) {
    event.preventDefault();

    if (!accepted) {
      alert("Please accept the terms and conditions.");
      return;
    }

    alert("Form submitted successfully.");
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        <input
          type="checkbox"
          checked={accepted}
          onChange={(event) => setAccepted(event.target.checked)}
        />
        I accept the terms and conditions.
      </label>
      <button type="submit">Continue</button>
    </form>
  );
}

export default TermsForm;

Remember: For checkboxes, use checked and event.target.checked, not value as a substitute for the checked state.


10. Handling Select Dropdown Events

The onChange event can handle dropdown selections. It is useful for choosing a country, course, category, city, or payment option.

Example

import { useState } from "react";

function CourseSelector() {
  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">React JS</option>
        <option value="javascript">JavaScript</option>
        <option value="node">Node.js</option>
      </select>

      <p>Selected course: {course || "None"}</p>
    </div>
  );
}

export default CourseSelector;

11. Handling Textarea Events

The textarea element collects longer text, such as feedback, comments, messages, and descriptions. In React, a controlled textarea uses value and onChange.

Example

import { useState } from "react";

function FeedbackForm() {
  const [feedback, setFeedback] = useState("");

  return (
    <div>
      <label htmlFor="feedback">Your feedback:</label>
      <textarea
        id="feedback"
        value={feedback}
        onChange={(event) => setFeedback(event.target.value)}
        placeholder="Write your feedback"
        rows={4}
      />
      <p>Characters entered: {feedback.length}</p>
    </div>
  );
}

export default FeedbackForm;

12. Handling Focus and Blur Events

The onFocus event runs when a field receives focus. The onBlur event runs when it loses focus. These events are useful for highlighting active fields and showing validation feedback.

Example

import { useState } from "react";

function EmailField() {
  const [email, setEmail] = useState("");
  const [touched, setTouched] = useState(false);

  const emailIsInvalid =
    touched && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);

  return (
    <div>
      <label htmlFor="email">Email address:</label>
      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        onBlur={() => setTouched(true)}
      />
      {emailIsInvalid && (
        <p>Please enter a valid email address.</p>
      )}
    </div>
  );
}

export default EmailField;

This example marks the field as touched when the user leaves it and then displays a basic validation message if the value does not match the expected email pattern. Client-side validation improves usability, but important validation must also be performed on the server.


13. Preventing Default Form Behaviour

HTML forms traditionally submit data using browser navigation. In many React applications, developers want to process the form with JavaScript instead. The event.preventDefault() method prevents the default submission behavior.

Example

function handleSubmit(event) {
  event.preventDefault();
  console.log("React is handling the form submission.");
}

Use preventDefault() when you want to handle the submission in a React event handler without the browser's usual form navigation. It does not automatically validate, save, or send data to a server.


14. Form Validation in React

Form validation checks whether user input is acceptable before an application processes it. React applications can combine built-in browser validation with custom JavaScript validation.

Common Validation Rules

  • Required fields must not be empty.
  • Email fields should contain a valid email format.
  • Password fields should meet the application's password rules.
  • Phone numbers should meet the expected format when applicable.
  • Checkboxes may need to be selected before continuing.
  • Values should be checked on the server before they are trusted or stored.

Example: Basic Required-Field Validation

import { useState } from "react";

function NameForm() {
  const [name, setName] = useState("");
  const [error, setError] = useState("");

  function handleSubmit(event) {
    event.preventDefault();

    if (name.trim() === "") {
      setError("Name is required.");
      return;
    }

    setError("");
    alert("Hello, " + name.trim());
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={name}
        onChange={(event) => setName(event.target.value)}
        placeholder="Enter your name"
      />
      {error && <p>{error}</p>}
      <button type="submit">Submit</button>
    </form>
  );
}

export default NameForm;

15. Resetting Form Fields

A reset action returns form fields to their initial values. With controlled components, reset the corresponding React state variables explicitly so the UI remains synchronized with the state.

Example

import { useState } from "react";

function ResetForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  function handleReset() {
    setName("");
    setEmail("");
  }

  return (
    <form onSubmit={(event) => event.preventDefault()}>
      <input
        value={name}
        onChange={(event) => setName(event.target.value)}
        placeholder="Name"
      />
      <input
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        placeholder="Email"
        type="email"
      />
      <button type="submit">Submit</button>
      <button type="button" onClick={handleReset}>Clear Form</button>
    </form>
  );
}

export default ResetForm;

The clear button uses type="button" so it does not accidentally submit the form.


16. Difference Between onChange and onSubmit

Feature onChange onSubmit
Purpose Handles field value changes. Handles form submission.
When it runs When the user changes a field's value. When the form is submitted.
Typical use Updating state and validating input. Validating all fields and processing form data.
Common element input, select, textarea form
Example onChange={handleChange} onSubmit={handleSubmit}

17. Complete React Form Example

The following example combines controlled inputs, change events, checkbox handling, validation, and form submission into one small registration form.

import { useState } from "react";

function RegistrationForm() {
  const [form, setForm] = useState({
    name: "",
    email: "",
    course: "",
    terms: false
  });
  const [message, setMessage] = useState("");

  function handleChange(event) {
    const { name, value, type, checked } = event.target;

    setForm((previousForm) => ({
      ...previousForm,
      [name]: type === "checkbox" ? checked : value
    }));

    setMessage("");
  }

  function handleSubmit(event) {
    event.preventDefault();

    if (!form.name.trim() || !form.email.trim() || !form.course) {
      setMessage("Please complete all required fields.");
      return;
    }

    if (!form.terms) {
      setMessage("Please accept the terms and conditions.");
      return;
    }

    setMessage("Registration form is ready to submit.");
    console.log("Registration data:", form);
  }

  return (
    <form onSubmit={handleSubmit}>
      <h2>Course Registration</h2>

      <label htmlFor="name">Full Name:</label>
      <input
        id="name"
        name="name"
        value={form.name}
        onChange={handleChange}
        required
      />

      <label htmlFor="email">Email:</label>
      <input
        id="email"
        name="email"
        type="email"
        value={form.email}
        onChange={handleChange}
        required
      />

      <label htmlFor="course">Course:</label>
      <select
        id="course"
        name="course"
        value={form.course}
        onChange={handleChange}
        required
      >
        <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>

      <label>
        <input
          type="checkbox"
          name="terms"
          checked={form.terms}
          onChange={handleChange}
        />
        I accept the terms and conditions.
      </label>

      <button type="submit">Register</button>

      {message && <p role="status">{message}</p>}
    </form>
  );
}

export default RegistrationForm;

What This Example Demonstrates

  • Controlled text inputs using React state.
  • Handling text, email, dropdown, and checkbox events.
  • Updating multiple state properties with one event handler.
  • Preventing the browser's default submission behavior.
  • Checking required fields and terms acceptance.
  • Showing a status message after the user submits the form.

Note: This example validates and logs the form data locally. It does not send the registration to a server or database. A production application should submit data to a suitable backend and validate it there as well.


18. Common Mistakes in React Form Event Handling

Mistake Problem Correct Approach
Using value without updating state The controlled input may not let the user edit its value. Update the state synchronously in onChange.
Using event.target.value for a checkbox It does not represent whether the checkbox is selected. Use event.target.checked.
Forgetting preventDefault() The browser may navigate or reload during a traditional form submission. Prevent the default behavior when handling submission in React.
Calling a handler immediately The function runs during rendering instead of when the event occurs. Use onChange={handleChange}.
Missing name attributes Fields may not be available under expected keys when using FormData. Give each submitted field a suitable name.
Using a submit button for clearing fields The clear action may also submit the form. Use type="button" for non-submit actions.
Relying only on client validation Client-side checks can be bypassed. Validate important data on the server as well.

19. Best Practices for Handling Form Events

  • Use controlled components when you need state-driven input values or live validation.
  • Use onChange to synchronize controlled fields with React state.
  • Use onSubmit to handle form submission in one place.
  • Call event.preventDefault() when you want to prevent normal browser form navigation.
  • Use semantic HTML elements such as form, label, input, and button.
  • Connect each label to its input using matching htmlFor and id values.
  • Use suitable input types such as email and password.
  • Provide clear validation messages that help users correct errors.
  • Keep related form state organized and use meaningful field names.
  • Never rely on client-side validation as the only security check.
  • Do not log sensitive values such as passwords in production.

20. Practical Applications of Form Events

  • Login form: Collecting a username or email and password.
  • Registration form: Collecting name, contact details, and course preferences.
  • Contact form: Collecting a user's name, email, and message.
  • Search form: Updating search criteria and processing the query.
  • Feedback form: Collecting comments and ratings.
  • Checkout form: Collecting delivery details and validating required fields.
  • Profile editor: Updating a user's information and saving changes.

21. Interview Questions and Answers

Q1. What are form events in React?

Form events are user interactions with form elements. React event handlers let developers respond to input changes, submissions, focus changes, and validation errors.

Q2. What is the purpose of onChange?

The onChange event handler responds when a form field's value changes. It is commonly used to update React state.

Q3. What is the purpose of onSubmit?

The onSubmit event handler processes a form submission. It can validate inputs, collect values, and begin a request to a backend service.

Q4. Why do we use event.preventDefault()?

It prevents the browser's default action for an event. For a form, it is commonly used to stop normal submission navigation while React handles the data.

Q5. What is a controlled component?

A controlled component is a form element whose current value is managed through React state and updated by an event handler.

Q6. What is an uncontrolled component?

An uncontrolled component keeps its current value in the DOM. React can read its value when needed, for example using a ref or the FormData API.

Q7. How do you get a text input's value?

Use event.target.value inside the input's event handler.

Q8. How do you get a checkbox's state?

Use event.target.checked, which returns a boolean indicating whether the checkbox is selected.

Q9. What is the difference between onChange and onSubmit?

onChange handles field value changes, whereas onSubmit handles submission of the entire form.

Q10. Can React handle validation?

Yes. React can implement custom validation using state and event handlers, and it can also use native browser constraints such as required and type="email". Server-side validation is still important.


22. Practice Exercises

  1. Create a username field that displays the entered text below the input.
  2. Create an email form and display a message when the email is invalid.
  3. Create a registration form with name, email, and password fields.
  4. Create a checkbox that enables a submit button only when selected.
  5. Create a dropdown for selecting a course and display the selected course.
  6. Create a feedback textarea that shows the current character count.
  7. Create a form with a clear button that resets all controlled inputs.
  8. Build a contact form that validates required fields and displays a success message.

23. Quick Revision Checklist

  • Understand what form events are and why they are useful.
  • Know how to use onChange and onSubmit.
  • Understand the React event object and event.target.value.
  • Know the difference between controlled and uncontrolled components.
  • Handle checkboxes with checked and event.target.checked.
  • Use event.preventDefault() when needed.
  • Understand form validation and how to reset controlled fields.
  • Practice building complete forms with multiple fields.

24. Conclusion

Handling Form Events is an important React JS skill for building interactive and user-friendly applications. By learning onChange, onSubmit, controlled and uncontrolled components, event objects, validation, and form state management, developers can create forms that collect information and respond correctly to user actions.

Practice these concepts by building login, registration, contact, search, and feedback forms. Always combine helpful client-side validation with appropriate server-side validation when processing real user data.


25. React JS Training and Course Demo

Learn more about React JS concepts, event handling, components, state management, and practical application development through the following course resources.

Previous Next
whatsapp