DEV Community

Cover image for Mastering Form Interactivity with React: A Comprehensive Guide for Developers
Muhammad Bilal
Muhammad Bilal

Posted on

Mastering Form Interactivity with React: A Comprehensive Guide for Developers

React

React has gained immense popularity among developers in recent years due to its numerous advantages:

Component-based architecture: React's component-based approach promotes code reusability, modularity, and easier maintenance, enabling developers to build complex applications efficiently.

Virtual DOM: React's virtual DOM optimizes rendering, improving performance by minimizing actual DOM manipulations.

Declarative syntax: React's declarative syntax simplifies UI development, allowing developers to focus on what the UI should look like based on its state, rather than managing low-level DOM manipulation.

Strong ecosystem: React has a vast and active ecosystem with extensive community support, providing developers with access to numerous libraries, tools, and resources to enhance development speed and efficiency.

Interactivity In Web Forms

Interactivity plays a crucial role in enhancing user experience and improving engagement on websites. Web forms, such as sign-up forms, contact forms, or checkout forms, are critical components of interactive web applications. Interactive web forms offer benefits such as:

Real-time feedback: Interactive forms provide instant feedback to users, reducing errors and improving the overall experience.

Dynamic user experience: Interactive elements, like auto-suggestions, input validation, or conditional fields, make forms more user-friendly and efficient.

Data accuracy: Interactive forms can include validation checks, ensuring that users provide correct and valid information, resulting in accurate data collection.

Setting Up a React Project With Vite

Installation of Vite: Install Vite globally or locally to leverage its features for creating React projects.

Project Initialization: Initialize a new React project with Vite using the command-line interface, providing a quick and streamlined setup.

Directory Structure: Understand the default directory structure created by Vite for React projects, organizing files for efficient development.

Importing Dependencies: Import necessary dependencies, such as React and Bootstrap, into the project to utilize their functionalities effectively.

# Install Vite globally
npm install -g create-vite

# Create a new React project with Vite
create-vite my-app --template react

# Change directory to the project folder
cd my-app

# Start the development server
npm run dev

Enter fullscreen mode Exit fullscreen mode

Building the Form Structure and Components

Designing the Form Layout: Create the structure and layout of the form using HTML and JSX syntax.

Creating Reusable Form Components: Break down the form into smaller, reusable components using React's component-based architecture.

Form Component Example: Provide an example of a form component, such as an input field or a checkbox, with corresponding JSX code.

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "../Styles/form.css";
export default function Form() {
  return(
<form className="p-3 mt-3" onSubmit={submitForm}>
  <div className="form-field d-flex align-items-center">
  <input type="text" name="userName" value={formData.userName} onChange={handleChange} id="userName" placeholder="Username" />
</div>

<!-- Email field -->
<div className="form-field d-flex align-items-center">
  <input type="email" name="userEmail" value={formData.userEmail} onChange={handleChange} id="userEmail" placeholder="Email" />
</div>

<!-- Password field -->
<div className="form-field d-flex align-items-center">
  <input type="password" name="password" value={formData.password} onChange={handleChange} id="password" placeholder="Password" />
</div>

<!-- Confirm password field -->
<div className="form-field d-flex align-items-center">
  <input type="password" name="confirmpassword" onChange={handleChange} id="confirmpassword" placeholder="Confirm Password" value={formData.confirmpassword} />
  {formData.passwordMatchError && (
    <div>Passwords do not match</div>
  )}
</div>
</form>
)
}

Enter fullscreen mode Exit fullscreen mode

Managing Form State with React Hooks

const [formData, setFormData] = React.useState({
  userName: "",
  userEmail: "",
  password: "",
  confirmpassword: "",
  checked: true,
  passwordMatchError: false,
});

Enter fullscreen mode Exit fullscreen mode

Input Change Handler in React

The handleChange function is responsible for handling changes in the input fields of the form. Let's break down the logic inside the handleChange function:

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

  setFormData((prevFormData) => ({
    ...prevFormData,
    [name]: type === "checkbox" ? checked : value,
    passwordMatchError: false,
  }));
}


Enter fullscreen mode Exit fullscreen mode

Destructuring Event Target:

const { name, value, type, checked } = event.target;
This line extracts the properties name, value, type, and checked from the event.target object. The event.target represents the input field that triggered the change event.

Updating the Form State:

setFormData((prevFormData) => ({ ...prevFormData, [name]: type === "checkbox" ? checked : value, passwordMatchError: false }))
The setFormData function is called to update the form state. It takes a callback function as an argument, which receives the previous form data (prevFormData). Inside the callback, a new object is created using the spread operator (...prevFormData) to copy the existing form data.

[name]: type === "checkbox" ? checked : value
This line dynamically sets the property of the formData object based on the input field's name property. If the input type is a checkbox (type === "checkbox"), it sets the value to checked; otherwise, it sets the value to value.

passwordMatchError: false
This line resets the passwordMatchError property to false in the form data state object. This is done to clear any previous password match error when a new input change occurs.

Form Submission

The submitForm function is triggered when the form is submitted. It prevents the default form submission behavior and checks if the password and confirm password fields match. If they match, it logs a success message; otherwise, it sets the passwordMatchError flag to true in the form data state and logs an error message.

function submitForm(event) {
  event.preventDefault();
  if (formData.password === formData.confirmpassword) {
    console.log("Successfully signed up");
  } else {
    setFormData((prevFormData) => ({
      ...prevFormData,
      passwordMatchError: true,
    }));
    console.log("Passwords do not match");
    return;
  }
}
Enter fullscreen mode Exit fullscreen mode

Complete Form

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "../Styles/form.css";

export default function Form() {
  // Form state
  const [formData, setFormData] = React.useState({
    userName: "",
    userEmail: "",
    password: "",
    confirmpassword: "",
    checked: true,
    passwordMatchError: false, // Tracks password match error
  });

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

    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: type === "checkbox" ? checked : value,
      passwordMatchError: false, // Reset password match error on each change
    }));
  }

  // Handle form submission
  function submitForm(event) {
    event.preventDefault();
    if (formData.password === formData.confirmpassword) {
      console.log("Successfully signed up");
    } else {
      setFormData((prevFormData) => ({
        ...prevFormData,
        passwordMatchError: true, // Set password match error if passwords do not match
      }));
      console.log("Passwords do not match");
      return;
    }
  }

  return (
    <div className="wrapper">
      <div className="logo">
        <img
          src="https://www.freepnglogos.com/uploads/amazon-png-logo-vector/world-brand-amazon-png-logo-vector-27.png"
          width="300"
          alt="world brand amazon png logo vector"
        />
      </div>
      <div className="text-center mt-4 name">Amazon Clone</div>
      <form className="p-3 mt-3" onSubmit={submitForm}>
        {/* Username field */}
        <div className="form-field d-flex align-items-center">
          <input
            type="text"
            name="userName"
            value={formData.userName}
            onChange={handleChange}
            id="userName"
            placeholder="Username"
          />
        </div>

        {/* Email field */}
        <div className="form-field d-flex align-items-center">
          <input
            type="email"
            name="userEmail"
            value={formData.userEmail}
            onChange={handleChange}
            id="userEmail"
            placeholder="Email"
          />
        </div>

        {/* Password field */}
        <div className="form-field d-flex align-items-center">
          <input
            type="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            id="password"
            placeholder="Password"
          />
        </div>

        {/* Confirm password field */}
        <div className="form-field d-flex align-items-center">
          <input
            type="password"
            name="confirmpassword"
            onChange={handleChange}
            id="confirmpassword"
            placeholder="Confirm Password"
            value={formData.confirmpassword}  
          />
          {formData.passwordMatchError && ( // Display error message conditionally
            <div>Passwords do not match</div>
          )}
        </div>

        {/* Terms and conditions checkbox */}
        <div className="text-center fs-6 form-market">
          <input
            type="checkbox"
            onChange={handleChange}
            name="checked"
            checked={formData.checked}
          />
          <label htmlFor="terms and conditions">
            Accept the Terms And Conditions
          </label>
        </div>

        {/* Submit button */}
        <button className="btn mt-3">Sign Up</button>
      </form>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

https://github.com/bilal1718

Top comments (0)