Forms in React, with or without React Forms

Forms in web development are like taxes: annoying but essential. Whether you’re gathering user information, processing payments, or letting someone sign up for yet another email newsletter they’ll ignore, forms are unavoidable.

If you’re reading this chances are you’ve wrestled with forms before. Let’s dive into how you can submit forms in React, comparing the classic “regular forms” approach with the shiny “React Form Component.” Spoiler alert: both have their peculiarities.

What do I need from my Form?

Before we jump into the nitty-gritty, let’s break down the main components you’ll need to consider when submitting a form:

  1. Data Validation: Ensuring users don’t submit garbage (like their email as “asdf@asdf.com“).
  2. Page Reload: Avoiding the dreaded full-page reload that’ll make your app look like it’s from 1995.
  3. Backend Request: Sending the form data to your backend without losing your sanity.

Both regular forms and the React Form Component handle these differently. Let’s dive in.

Regular Forms

Using a regular HTML form in React is straightforward. It’s a classic, like wearing socks with sandals (but less embarrassing).

const export RegularForm = () => {
  const handleSubmit = (event) => {
    event.preventDefault(); // Stops the page reload
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData);
    console.log(data); // Do something with the data
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" name="name" required />
      </label>
      <br />
      <label>
        Email:
        <input type="email" name="email" required />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

What Makes Regular Forms Work?

  1. Validation: HTML5 comes with built-in validation for common inputs like email, number, and required. Simple, but if you want complex validation (e.g., passwords with emojis), you’re on your own.
  2. Page Reload: Preventing the default form submission behavior is your responsibility. Forget that event.preventDefault(), and your app takes users on an unexpected nostalgia trip.
  3. Backend Request: You grab the data using the FormData API and manually send it using fetch or some other library. It’s all up to you.

Pros and Cons of Regular Forms

Pros:

  • Simplicity. If it ain’t broke, don’t fix it.
  • No extra libraries or dependencies.

Cons:

  • Validation beyond HTML5? Roll up your sleeves.
  • Handling the state can be tricky if you want dynamic feedback.

React Form Component

React’s ecosystem is home to libraries like react-hook-form or formik, which take the pain out of form handling (mostly). These libraries do more than hold your hand, they basically fill out the form for you.

import { useForm } from 'react-hook-form';

const export ReactForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const onSubmit = (data) => {
    console.log(data); // Do something with the data
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>
        Name:
        <input {...register("name", { required: "Name is required" })} />
      </label>
      {errors.name && <p>{errors.name.message}</p>}
      <br />

      <label>
        Email:
        <input
          {...register("email", {
            required: "Email is required",
            pattern: {
              value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
              message: "Invalid email address",
            },
          })}
        />
      </label>
      {errors.email && <p>{errors.email.message}</p>}
      <br />

      <button type="submit">Submit</button>
    </form>
  );
}

Why React Form Libraries Are Awesome

  1. Validation: You get powerful validation options out of the box. Want to check if the user’s email ends in .io? Go for it.
  2. Default Values: Libraries like react-hook-form let you prefill forms with default values. Your users will thank you for sparing their fingers.
  3. Submission: Form libraries streamline data collection and validation, so you’re not manually parsing FormData like a caveman.

Pros and Cons of React Form Libraries

Pros:

  • Built-in validation that’s way more powerful than HTML5.
  • Easier to manage form state and dynamic behavior.

Cons:

  • Higher learning curve. It’s not rocket science, but it’s close.
  • You’re adding another dependency to your project.

Conclusion

When deciding between regular forms and the React Form Component, ask yourself this:

  • Are you working on a simple form with basic validation? Stick with regular forms. They’re easy, lightweight, and less likely to make you question your career choices.
  • Is your form a labyrinth of conditional fields, advanced validation, and dynamic behavior? Invest the time in a React form library. It’ll save you hours (and tears) in the long run.

Forms don’t have to be a nightmare, but let’s face it, they’ll never be a dream. Choose the approach that fits your needs, and remember: no matter how painful it gets, at least you’re not debugging Internet Explorer.


Never Miss Another Tech Innovation

Concrete insights and actionable resources delivered straight to your inbox to boost your developer career.

My New ebook, Best Practices To Create A Backend With Spring Boot 3, is available now.

Best practices to create a backend with Spring Boot 3

Leave a comment

Discover more from The Dev World - Sergio Lema

Subscribe now to keep reading and get access to the full archive.

Continue reading