Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 37

Controlling Form Submissions

Recommended resources

Hello! Welcome to your fifth lesson in the "Forms and Event Handling" module.

In our last session, we built a robust and scalable pattern for managing the state of a form with multiple inputs using a single state object and a universal handleChange function. Now that we can efficiently collect user input, it's time to handle the final step in the form's lifecycle: submission.

This lesson focuses on the learning outcome: Handle form submission, including preventing default browser behavior. We'll explore why a standard HTML form submission is disruptive in a React application and how to take full control of the process.

1. The Default Behavior of HTML Forms

Let's start by adding a submit button to the multi-input form we conceptualized in the previous lesson. A standard HTML form is typically wrapped in a <form> tag, and submission is triggered by a <button type="submit"> or by pressing "Enter" in an input field.

// Continuing our RegistrationForm example from the last lesson

function RegistrationForm() {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // We will define this function shortly
  const handleSubmit = () => {
    alert('Form submitted!'); // Placeholder
  };

  return (
    // We add the <form> tag here
    <form> 
      {/* ...our input fields for firstName, lastName, email ... */}
      <button type="submit">Register</button>
    </form>
  );
}

If you were to run this code and click the "Register" button, you would notice the page momentarily flashes and reloads. This is the default browser behavior for form submission. The browser attempts to send the form data to the server (or the current page URL if no action attribute is specified) via an HTTP request, which results in a full page refresh.

In a Single Page Application (SPA) built with React, this is highly undesirable. We want to manage UI updates and data flow within our application's memory without losing state or forcing a disruptive page reload.


2. Preventing Default Behavior with event.preventDefault()

To stop the browser's default form submission behavior, React provides a mechanism that mirrors the standard Web API: the onSubmit event handler. By attaching a handler function to the <form> element's onSubmit prop, we can intercept the submission event.

Inside this handler, the event object (e) has a crucial method: e.preventDefault(). Calling this method tells the browser, "Don't do your default action for this event."

Responding to Events

The official React documentation has a clear and concise section on this exact topic. Let's read it to solidify our understanding of the fundamental mechanism.

In the article, find and read the section titled 'Preventing default behavior'. Focus on the example provided for the <form> element and the explanation of e.preventDefault().

Now, let's apply this to our RegistrationForm.

We'll define a handleSubmit function and pass it to the <form>'s onSubmit prop.

import { useState } from 'react';

// Assume UserProfile interface and form inputs are defined as before

function RegistrationForm() {
  const [formData, setFormData] = useState<UserProfile>({
    firstName: '',
    lastName: '',
    email: '',
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // ... same as before
  };

  // 1. The event object is passed to our handler automatically
  const handleSubmit = (e: React.FormEvent) => {
    // 2. We call preventDefault() to stop the page reload
    e.preventDefault();

    // 3. Now we can handle the data ourselves!
    console.log('Form submitted with data:', formData);
    alert(`Thank you for registering, ${formData.firstName}!`);
  };

  return (
    // 4. We attach our handler to the form's onSubmit event
    <form onSubmit={handleSubmit}>
      {/* ...input fields... */}
      <button type="submit">Register</button>
    </form>
  );
}

With e.preventDefault() in place, clicking the submit button no longer reloads the page. Instead, our handleSubmit function executes, and we gain full control. Because we're using controlled components, the complete and current state of the form is already available in our formData object. We can now use this data to make an API call, update parent component state, or perform any other action.

Why onSubmit on the <form> instead of onClick on the <button>?
Placing the handler on the <form> is best practice because it covers all standard methods of form submission, including a user pressing the "Enter" key inside an input field. An onClick handler on the button would miss that case.


3. Typing the Submission Event

You'll notice in the code above, we typed the event parameter as e: React.FormEvent. Your proficiency with TypeScript makes this a critical detail. Without a type, TypeScript would complain that e implicitly has an any type.

While you could use a more generic React.SyntheticEvent, using React.FormEvent is more specific and accurate. It correctly types e.currentTarget as an HTMLFormElement, giving you better type safety if you need to interact with the form element itself.

React & TypeScript - Course for Beginners

Let's watch a short clip that demonstrates this exact process in a React and TypeScript context. It shows how you'd typically arrive at the correct type for a form submission event.

Watch from 00:32:29 to 00:35:20. The video shows how a developer might encounter the TypeScript error, search for the solution, and apply the React.FormEvent type to both the handler function and its prop definition.


4. A Deeper Dive into Form Typing (The Kent C. Dodds Method)

In our controlled component pattern, accessing the form data is simple: just use the state variable (formData).

However, in some less common scenarios (often called "uncontrolled components"), you might need to access form data directly from the DOM elements upon submission. While we advocate for controlled components, understanding how to handle this alternative pattern in a type-safe way will deepen your expertise.

This is where your TypeScript background will be particularly beneficial. A naive approach might involve messy type assertions (as). A much cleaner method exists.

How to type a React form onSubmit handler

Kent C. Dodds, a well-known figure in the React community, wrote an excellent article on precisely this topic. It shows a progression from a basic, less-than-ideal typing approach to a highly elegant and type-safe solution.

Please read the entire article. It's short but dense with valuable information. Notice the initial approach using React.SyntheticEvent and a clunky type assertion (as). See the first improvement to React.FormEvent. Pay close attention to the final, recommended solution where he creates custom interfaces that extend HTMLFormElement and HTMLFormControlsCollection. This completely eliminates the need for type assertions and makes the handleSubmit function itself much cleaner.

The key takeaway from that article is that you can provide TypeScript with a more detailed "shape" of your specific form, allowing it to help you more effectively. For instance:

// The advanced pattern from the article
interface MyFormElements extends HTMLFormControlsCollection {
  email: HTMLInputElement;
  firstName: HTMLInputElement;
}

interface MyCustomForm extends HTMLFormElement {
  readonly elements: MyFormElements;
}

// Your submit handler now gets perfect type inference
const handleSubmit = (event: React.FormEvent<MyCustomForm>) => {
  event.preventDefault();
  const email = event.currentTarget.elements.email.value;
  const firstName = event.currentTarget.elements.firstName.value;
  console.log({ email, firstName }); // Type-safe!
}

Again, for most of your work, relying on the state from your controlled components is the standard and recommended React pattern. But understanding this advanced typing method for direct DOM access gives you a powerful tool for edge cases and showcases a truly professional approach to TypeScript in React.

Test your understanding!

A colleague writes the following code and is confused why the page still reloads when they click "Submit". What is the bug?

function BuggyForm() {
  const handleSubmit = (e: React.FormEvent) => {
    // They forgot to call the method!
    e.preventDefault; 
    console.log('Submitting...');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="test" />
      <button type="submit">Submit</button>
    </form>
  );
}
Show answer

The bug is e.preventDefault;. preventDefault is a method, not a property. It needs to be called as a function: e.preventDefault(). By just referencing the method without invoking it with parentheses, the default browser action is never actually prevented, and the page reloads as usual.


Conclusion

You have now mastered the complete lifecycle of a simple controlled form in React: capturing user input into state, and now, handling the submission of that state.

Key Takeaways:

  • By default, HTML form submissions cause a full page reload, which is undesirable in a React SPA.
  • To take control, use the onSubmit event handler on the <form> element.
  • Inside the handler, call event.preventDefault() as the very first step to stop the browser's default behavior.
  • In a controlled component, the complete form data is already available in your state object at the time of submission.
  • Use the React.FormEvent type for your submission handler's event parameter to ensure type safety.

In our next lesson, we'll address a crucial part of creating a user-friendly form: implementing client-side form validation. We'll see how to check the user's input for errors before we attempt to submit it, and how to provide clear feedback.