Back
React
Mon Jul 29 2024

An Introduction to Basic Form Handling in ReactJS

Handling forms in ReactJS involves managing the form state and ensuring that the state accurately reflects the current values of the input fields. Unlike traditional HTML form handling, where the browser takes care of form state and submission, React manages the form state explicitly. This provides more control and flexibility over form behaviors and validations.

React forms can be handled using either controlled or uncontrolled components. Form data is handled by the component's state in a controlled component whereas uncontrolled components rely on the DOM to handle the form data.

The following are the examples of handling input fields using controlled components.

 

Handling input fields

Handling input fields in React involves managing the form state and ensuring that the state reflects the current value of the input fields. Controlled components are the recommended approach for handling forms. First we initialize the state to hold the values of the form in the controlled component.

Implementation

import React, { useState } from "react";

const Form = () => {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  function handleFirstName(e) {
    setFirstName(e.target.value);
  }
  function handleLastName(e) {
    setLastName(e.target.value);
  }

  return (
    <div>
      <form>
        <input
          type="text"
          value={firstName}
          onChange={(e) => handleFirstName(e)}
        />
        <input
          type="text"
          value={lastName}
          onChange={(e) => handleLastName(e)}
        />
      </form>

      <p>
        Your name is {firstName} {lastName}.
      </p>
    </div>
  );
};

export default Form;

In the above example, we create a form that takes user's first and last name and renders it on the screen. The input fields 'firstName' and 'lastName' are managed using the useState hook in React. The 'onChange' handles the events and updates the state variables whenever the input changes. The rendering is also different according to the input values.

 

Handling form submission

Handling form submission in ReactJS is a fundamental skill for creating interactive and dynamic web applications. This involves capturing user input, managing state, and processing the form data when the user submits it. A typical form in React consists of various input fields and a submit button. Each input field is controlled by the component's state using the useState hook. This ensures that the form data is managed within the React component and can be easily accessed and manipulated.

Implementation

import React, { useState } from "react";

const Form = () => {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [address, setAddress] = useState({ city: "", country: "" });

  function handleFirstName(e) {
    setFirstName(e.target.value);
  }
  function handleLastName(e) {
    setLastName(e.target.value);
  }
  function handleSubmit(e) {
    e.preventDefault();
    console.log("First Name:", firstName);
    console.log("Last Name:", lastName);
    console.log("Address:", address);

    //Reset values
    setFirstName("");
    setLastName("");
    setAddress({ city: "", country: "" });
  }

  return (
    <div>
      <form>
        <label>First Name:</label>
        <input
          type="text"
          value={firstName}
          onChange={(e) => handleFirstName(e)}
        />
        <label>Last Name:</label>
        <input
          type="text"
          value={lastName}
          onChange={(e) => handleLastName(e)}
        />
        <label>City:</label>
        <input
          onChange={(e) => setAddress({ ...address, city: e.target.value })}
          type="text"
          value={address.city}
        />
        <label>Country:</label>
        <input
          onChange={(e) => setAddress({ ...address, country: e.target.value })}
          type="text"
          value={address.country}
        />
      </form>
      <button onClick={(e) => handleSubmit(e)}>Submit</button>
    </div>
  );
};

export default Form;

The above example demonstrates a simple form component in React that captures user input for a first name, last name, city, and country. It manages the form data using the useState hook, handles input changes, and logs the form data upon submission.

 

Conclusion

Handling forms in ReactJS requires an understanding of controlled and uncontrolled components. By using controlled components, you gain more control over the form state and can easily implement form validation and submission handling. The examples provided in this post should give you a solid foundation for managing forms in your React applications.