---
title: "React Form"
url: https://khanwaseem.com/blog/course/react-form
author: "khan Waseem"
published: 2023-10-19
updated: 2023-10-26
topics: ["course", "React Tutorial"]
description: "Master React form handling. Learn to create interactive and responsive forms for user input in your web applications."
---

# React Form

Forms are a fundamental part of web applications. They allow users to input data, interact with your application, and provide valuable information. In the world of React, creating and managing forms is a crucial skill for building interactive user interfaces. In this blog post, we’ll explore the ins and outs of working with forms in React, from the basics of form elements to handling user input and form submission.

Table of Contents

[Toggle](#)

- [Basics of HTML Forms](#basics-of-html-forms)[Creating a Basic HTML Form](#creating-a-basic-html-form)
- [Handling Forms in React](#handling-forms-in-react)
- [Step 1: Create a Form Component](#step-1-create-a-form-component)
- [Step 2: State for Form Data](#step-2-state-for-form-data)
- [Step 3: Handle Form Input Changes](#step-3-handle-form-input-changes)
- [Step 4: Handle Form Submission](#step-4-handle-form-submission)
- [Step 5: Connect Form Elements to State](#step-5-connect-form-elements-to-state)
- [Step 6: Handle Form Submission](#step-6-handle-form-submission)
- [Validating Form Input](#validating-form-input)
- [Form Libraries in React](#form-libraries-in-react)
- [Conclusion](#conclusion)

## Basics of HTML Forms

Before diving into React-specific form handling, it’s essential to understand the basics of HTML forms. In traditional HTML, a form consists of various elements, including:

- **`<form>`**: The `**<form>**` element is used to create a form container that wraps all the form elements. It specifies the action (the URL where the form data is sent) and the method (typically **`GET` **or `**POST**`) for the form.

- **`<input>`**: The `**<input>**` element is the most common form element for text input. It serves various purposes, such as capturing single-line text, managing password inputs, and handling email input, among others. You can specify the `type` attribute to define the input’s behavior.

- **`<textarea>`**: The `**<textarea>**` element is used for multi-line text input. It allows users to input longer pieces of text.

- **`<select>`**: The `**<select>**` element creates a dropdown list from which users can choose an option. It contains one or more `**<option>**` elements.

- **`<button>`**: The `**<button>**` element can be used to create clickable buttons for form submission or other actions.

- **`<label>`**: The `**<label>**` element provides a label for form elements. It improves accessibility and user experience by associating the label with the input element.

### Creating a Basic HTML Form

Here’s an example of a basic HTML form:

```xml
<!DOCTYPE html>
<html>
  <head>
    <title>Basic HTML Form</title>
  </head>
  <body>
    <h1>Contact Us</h1>
    <form action="/submit" method="POST">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" required>

      <label for="email">Email:</label>
      <input type="email" id="email" name="email" required>

      <label for="message">Message:</label>
      <textarea id="message" name="message" rows="4" required></textarea>

      <button type="submit">Submit</button>
    </form>
  </body>
</html>Code language: HTML, XML (xml)
```

In this HTML form, we have input fields for name, email, and a message, along with a submit button. When users enter data and click the “Submit” button, the form sends the data to the server for processing.

### Handling Forms in React

In React, forms are managed differently compared to traditional HTML forms. React’s component-based architecture allows us to create interactive and dynamic forms with ease. Here’s a step-by-step guide to handling forms in React:

### Step 1: Create a Form Component

Start by creating a new component for your form. You can use either a functional or class component. For this example, we’ll use a functional component.

```javascript
import React, { useState } from 'react';

function ContactForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: '',
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    // Handle form submission here
  };

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input
        type="text"
        id="name"
        name="name"
        value={formData.name}
        onChange={handleChange}
        required
      />

      <label htmlFor="email">Email:</label>
      <input
        type="email"
        id="email"
        name="email"
        value={formData.email}
        onChange={handleChange}
        required
      />

      <label htmlFor="message">Message:</label>
      <textarea
        id="message"
        name="message"
        rows="4"
        value={formData.message}
        onChange={handleChange}
        required
      ></textarea>

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

export default ContactForm;Code language: JavaScript (javascript)
```

**Output : **

![React Form Example](https://blogkhanwaseem.s3.amazonaws.com/uploads/2023/10/19222158/image-44-1024x231.png)

### Step 2: State for Form Data

In the **`ContactForm` **component, we initialize state using the **`useState` **hook to manage form data. The **`formData` **state object contains properties for name, email, and message. We use the **`setFormData` **function to update this state.

### Step 3: Handle Form Input Changes

The **`handleChange` **function is called whenever an input field changes. It extracts the **`name` **and **`value` **from the event target and updates the **`formData` **state with the new value. This allows real-time updates as the user types.

### Step 4: Handle Form Submission

The **`handleSubmit` **function is called when the user submits the form. We prevent the default form submission using **`e.preventDefault()` **to handle the submission manually. You can add your own logic for form submission, such as making an API request.

### Step 5: Connect Form Elements to State

Each form element (input and textarea) is connected to the state. We set the **`value` **prop of each element to the corresponding property in the **`formData` **state. This ensures that the input fields display the current values from the state.

### Step 6: Handle Form Submission

When the user clicks the “Submit” button, the **`handleSubmit` **function is called. You can add your own logic here to process the form data. This can include sending the data to a server, performing client-side validation, or any other actions required for your application.

### Validating Form Input

Data validation is a crucial part of form handling. You want to ensure that the data entered by the user is valid before submitting it. React provides an excellent way to perform validation by setting rules and conditions for form elements.

For instance, you can add the **`required` **attribute to input fields to make them mandatory. Additionally, you can use JavaScript functions to validate data further. Here’s an example of adding validation to the email input:

```xml
<input
  type="email"
  id="email"
  name="email"
  value={formData.email}
  onChange={handleChange}
  required
  pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
/>Code language: HTML, XML (xml)
```

In this example, we’ve added the **`pattern` **attribute with a regular expression to validate the email format. If the user enters an invalid

email address, the browser will display a validation message.

### Form Libraries in React

As your forms become more complex, you might consider using form libraries like Formik or react-hook-form. These libraries provide additional features for form validation, form submission, and handling complex form states.

### Conclusion

React empowers you to create dynamic and interactive forms with ease. By understanding the basics of form elements and how to manage form data, you can build user-friendly and responsive forms for your web applications.

So, go ahead, experiment with form handling in React, and build amazing user interfaces that gather user input effectively and provide a seamless experience for your users. Whether it’s a simple contact form or a complex data entry form, React has you covered.

### Related posts:

[HTML – Forms](https://blog.khanwaseem.com/html-forms/)
[JavaScript – Form](https://blog.khanwaseem.com/javascript-form-validation/)
[JavaScript-Form properties and methods](https://blog.khanwaseem.com/javascript-form-properties-and-methods/)
[React Redux](https://blog.khanwaseem.com/react-redux/)

Powered by [YARPP](https://yarpp.com).
