Skip to main content

Welcome to a Grasp lesson

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

Lesson 36

Form Submission and Default Prevention

Recommended resources

Hello! Let's dive into our next lesson.

In our last session, we mastered the art of creating "controlled components," ensuring that our React state is the single source of truth for our form inputs. You now know how to manage the data within text fields, select dropdowns, and checkboxes using the useState hook.

Today, we'll address the next logical step: what to do when the user hits "Submit." Our goal is to handle form submission, including preventing the default browser behavior. This is a fundamental concept in building Single-Page Applications (SPAs). With your background in Laravel, you're likely familiar with traditional forms that trigger a full-page reload upon submission. In React, we'll intercept that process to create a seamless, modern user experience.

1. Capturing the Submission Event

First, we need a way to listen for when the user submits the form. While you could put an onClick handler on the submit button, the more robust and accessible method is to attach an onSubmit event handler directly to the <form> element. This captures all submission methods, including a user pressing the "Enter" key inside an input field.

This short video from Net Ninja introduces the onSubmit event and how to wire it up to a handler function.

Full React Tutorial #28 - Submit Events

Watch this first segment from the "Full React Tutorial #28 - Submit Events" video. It explains why using onSubmit on the form is the preferred approach.

Watch from 00:07 to 00:58. Focus on how the onSubmit attribute is added to the <form> tag and linked to a handleSubmit function.

As you saw, the pattern is straightforward:

const handleSubmit = (event) => {
  // We'll add logic here soon
  console.log("Form was submitted!");
};

return (
  <form onSubmit={handleSubmit}>
    {/* ... your form inputs ... */}
    <button type="submit">Submit</button>
  </form>
);

Notice that the handleSubmit function automatically receives an event object as its first argument. This object is the key to our next step.


2. Preventing the Default Behavior

If you were to run the code above, you'd notice the browser tab still refreshes when you submit the form, and you might only catch a fleeting glimpse of the console message. This is the browser's default behavior for form submissions. In a React SPA, we need to stop this.

The solution is to call the preventDefault() method on the event object.

Responding to Events

The official React documentation provides the most direct explanation for this. Please read the following section from the article "Responding to Events".

Read the section titled "Preventing default behavior". It's short but contains the essential concept and a clear code example.

To see this in action, let's return to the Net Ninja video.

Full React Tutorial #28 - Submit Events

This next clip demonstrates exactly how to implement event.preventDefault() within the handler function you just created.

Watch from 00:58 to 01:30. Observe how adding one line of code, event.preventDefault(), changes the form's behavior completely.

The handleSubmit function should now look like this, with event.preventDefault() as its very first line.

const handleSubmit = (event) => {
  // 1. Prevent the default browser action (page reload)
  event.preventDefault();

  // 2. Now we can run our own logic
  console.log("Form submitted without reloading!");
};

This simple method is crucial for building SPAs. It allows your React application to take full control, process data, update the UI, and communicate with a server (like your Laravel backend) without the disruptive experience of a full page refresh.

This diagram helps visualize the flow: a user's action triggers the onSubmit event, which is caught by your handler, where you can then call preventDefault().

User Action to Event Handler Flowchart
This flowchart shows the process from a user action to an event handler. The `onSubmit` event is handled, where we can use `preventDefault()` to control the outcome.

3. Consolidating and Using Form Data

Now that we've prevented the page from reloading, we can finally do something useful with the data from our controlled inputs. Since the values are already stored in state variables, the next step inside handleSubmit is to gather them into a single object. This object is what you'll typically send to an API or use to update application state.

This final clip from the Net Ninja video shows how to create this data object.

Full React Tutorial #28 - Submit Events

Watch this segment to see how to collect the values from your state variables into a clean object upon submission.

Watch from 01:30 to 02:31. Pay attention to how the state variables for title, body, and author are combined into a new blog object inside the handleSubmit function.

Let's combine everything we've learned in the last two lessons into a complete, working example:

import { useState } from 'react';

function SimpleContactForm() {
  const [name, setName] = useState('');
  const [message, setMessage] = useState('');

  const handleSubmit = (event) => {
    // Step 1: Prevent the page from reloading
    event.preventDefault();

    // Step 2: Consolidate the data from state into an object
    const formData = {
      name: name,
      message: message,
    };

    // Step 3: Do something with the data (e.g., log it or send to an API)
    console.log("Form Data Submitted:", formData);
    alert(`Thank you, ${formData.name}! Your message has been received.`);

    // Optional: Clear the form fields after submission
    setName('');
    setMessage('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Name:</label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </div>
      <div>
        <label>Message:</label>
        <textarea
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        />
      </div>
      <button type="submit">Send</button>
    </form>
  );
}

In this example, upon submission, we prevent the reload, package our name and message states into a formData object, and then log it to the console and show an alert. Finally, we reset the state variables to empty strings, which automatically clears the controlled input fields, making the form ready for another submission.


Conclusion

You've now bridged the gap between managing form inputs and acting on user submission. This is a critical skill for building any interactive feature, from a simple contact form to a complex e-commerce checkout.

Key Takeaways:

  • Use the onSubmit event handler on the <form> element to capture form submissions reliably.
  • Your handler function receives an event object automatically.
  • Always call event.preventDefault() as the first step in your submission handler to stop the browser from reloading the page.
  • After preventing the default behavior, you can gather your form data from your state variables and proceed with your application's logic.

Preview of Next Lesson:
Our form works, but it blindly accepts any input. What if the user submits a blank name or message? In our next lesson, we will focus on implementing client-side validation logic and displaying error messages to provide better user feedback and ensure data quality before submission.