Form handling is an essential part of any web application, and React allows us to make it more interactive and dynamic. In React, there are two main ways to handle forms: controlled components and uncontrolled components. In this blog post, we will explore both approaches and learn how to effectively handle forms in React.

Forms are inherently interactive elements in HTML, designed to allow users to interact with a web page. Common use cases for forms include search functionality, contact forms, shopping cart checkouts, login and registration forms, and more.

Controlled Components

Controlled components are the preferred way of handling forms in React. In this approach, the component state becomes the single source of truth for the form data. When an element’s state changes in a form field managed by a component, we track it using the onChange attribute.

Here’s an example of how to handle a form using controlled components:

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = { username: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ username: event.target.value });
  }

  handleSubmit(event) {
    alert(this.state.username);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          value={this.state.username}
          onChange={this.handleChange}
        />
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

To set the new state in a class component, we need to bind this to the corresponding class method. This ensures that this is accessible within the method.

Uncontrolled Components

Uncontrolled components are used when certain form fields have inherently uncontrolled behavior, such as the <input type="file"> field. In this approach, the form data is managed by the DOM rather than the component state.

Here’s an example of how to handle an uncontrolled component:

class FileInput extends React.Component {
  constructor(props) {
    super(props);
    this.curriculum = React.createRef();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    alert(this.curriculum.current.files[0].name);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="file" ref={this.curriculum} />
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

In this example, the uploaded file is accessed using a reference (this.curriculum) assigned to the ref attribute of the file input. The form data is stored in the DOM, and we haven’t touched the component’s state.

Simplifying Form Handling with Hooks

With the introduction of hooks in React, handling forms becomes even simpler and more concise. Hooks allow us to use state and other React features without writing a class component.

Here’s an example of how to handle a form using hooks:

import React, { useState } from 'react';

const Form = () => {
  const [username, setUsername] = useState('');

  const handleChangeUsername = (event) => {
    setUsername(event.target.value);
  };

  const handleSubmit = (event) => {
    alert(username);
    event.preventDefault();
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={username}
        onChange={handleChangeUsername}
      />
      <input type="submit" value="Submit" />
    </form>
  );
};

Using hooks, we can manage state and handle form data without the need for a class component. The useState hook is used to declare a state variable (username), and the handleChangeUsername and handleSubmit functions are used to update the state and handle form submissions, respectively.

Advanced Form Handling with Formik

While React provides us with the tools to handle forms effectively, there are libraries that simplify and automate form handling further. One such library is Formik, which offers features like validation, error handling, and more.

Handling forms in React becomes more efficient and streamlined with the knowledge of controlled components, hooks, and libraries like Formik. Whether you choose to use controlled or uncontrolled components, React empowers you to create interactive and dynamic forms for your web applications.

Tags: React, Forms, Controlled Components, Uncontrolled Components, Hooks, Form Handling, Formik