How To Create a React.js Form

Udemezue John - Oct 6 - - Dev Community

Introduction.

Creating forms in React.js might seem like a daunting task at first, but with the right approach, it's actually quite manageable.

Forms are essential in almost every web application—think login forms, search bars, checkout pages, and more.

In fact, user interaction through forms is what transforms static websites into dynamic, data-driven applications. That’s why it’s crucial to master this skill when working with React.

React offers a variety of ways to handle forms, but at its core, the process revolves around managing state efficiently and ensuring that user inputs are correctly handled.

React's component-driven architecture provides a way to seamlessly integrate form controls and validations while maintaining a clean, organized codebase.

Plus, React's virtual DOM makes handling form re-renders efficient, so you don’t have to worry about performance even as your forms grow in complexity.

In this post, I’ll walk through the step-by-step process of creating a basic form in React.

How do I Create a React.js Form?

Building forms is a core part of web development, and when using React.js, the process is straightforward yet powerful.

React allows me to create dynamic, interactive forms that are easy to manage, scale, and maintain.

Whether I’m collecting user input for a simple contact form or handling complex form validations for a larger application, React forms provide flexibility and a streamlined development experience.

In this guide, I’ll walk through how to build a form in React, step by step.

Prerequisites

Before jumping into form creation, it’s important to ensure that I have the following:

  • Node.js and npm installed: React requires Node.js, and npm (Node Package Manager) helps manage dependencies.
  • Basic understanding of React concepts: Concepts like state, props, and event handling should be familiar to get the most out of this guide.

Note:

Make sure to replaced the '' with the backtick in the when trying to console, I had to change it because I kept getting errors when trying to publish here on Dev.to.

Step 1: Setting up a React Project.

First, I need to set up a React project. If I don't already have one, I can create a new project using Create React App.

npx create-react-app react-form
cd react-form
npm start
Enter fullscreen mode Exit fullscreen mode

Once this is done, the development server will start, and I can see the default React app at http://localhost:3000.

Step 2: Building a Simple Form.

To start, I'll create a simple form that collects basic user information such as name and email.

The first step is to create a new component, Form.js, that will contain my form:

import React, { useState } from "react";

const Form = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Name: ${name}, Email: ${email}');
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Name:</label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
        />
      </div>
      <div>
        <label>Email:</label>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default Form;
Enter fullscreen mode Exit fullscreen mode

In this component:

I’m using React’s useState hook to manage the form’s state.

The handleSubmit function is called when the form is submitted, preventing the default form behaviour and logging the input values to the console.

This basic form captures the user's name and email and submits the data when the user clicks the submit button.

Step 3: Controlled Components.

React forms use controlled components, where the form elements' values are tied to the component state.

This means I need to ensure that every input field is connected to the state via the value attribute and that I update the state whenever the input changes.

In the code above, each input element is controlled by the state (name and email).

When the user types something in the input field, the onChange event triggers an update to the corresponding state.

Step 4: Handling Form Validation.

Now, I'll add some basic validation to ensure the user fills out the form correctly. React doesn’t come with built-in form validation, so I’ll add my logic:

const Form = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    // Simple validation
    if (!name || !email.includes("@")) {
      setError("Please provide a valid name and email.");
    } else {
      setError("");
      console.log('Name: ${name}, Email: ${email}');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {error && <p style={{ color: "red" }}>{error}</p>}
      <div>
        <label>Name:</label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
        />
      </div>
      <div>
        <label>Email:</label>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

Enter fullscreen mode Exit fullscreen mode

Now, when the user submits the form, I perform a simple check to ensure the name isn't empty and the email contains an "@" symbol.

If the validation fails, an error message is displayed above the form.

Conclusion.

Creating forms in React.js involves managing state, handling form submissions, and validating user inputs—all while keeping everything under control using React’s declarative approach.

While React’s built-in tools are great for simple forms, using libraries like React Hook Form or Formik can simplify more complex scenarios.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player