[React.js] - Part 7. React Forms

Ace Lennox
20 Jan 20253 minutes to read

React forms are similar to HTML forms but provide more flexibility and control by using state and event handlers. This guide will show you how to handle forms in React with practical examples.


1. Adding Forms in React

In React, you can create forms just like you would in HTML:

Example: A Simple Form

function MyForm() {
  return (
    <form>
      <label>
        Enter your name:
        <input type="text" />
      </label>
    </form>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyForm />);

This form works, but when you submit it, the page refreshes. In React, we usually prevent this behavior and let React handle the form submission.


2. Controlled Components

A controlled component in React is an input element whose value is controlled by React state. You can use the useState Hook to track the input’s value and provide a "single source of truth."

Example: Managing Input State

import { useState } from "react";
import ReactDOM from "react-dom/client";

function MyForm() {
  const [name, setName] = useState("");

  return (
    <form>
      <label>
        Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
    </form>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyForm />);

3. Submitting Forms

You can handle the form submission by using the onSubmit event and preventing the default browser behavior.

Example: Handling Form Submission

import { useState } from "react";
import ReactDOM from "react-dom/client";

function MyForm() {
  const [name, setName] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`You entered: ${name}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyForm />);

4. Multiple Input Fields

To handle multiple input fields, initialize your state as an object. Use the name attribute on each input field to identify it and update the state dynamically.

Example: Form with Multiple Inputs

import { useState } from "react";
import ReactDOM from "react-dom/client";

function MyForm() {
  const [inputs, setInputs] = useState({});

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

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(JSON.stringify(inputs));
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Enter your name:
        <input
          type="text"
          name="username"
          value={inputs.username || ""}
          onChange={handleChange}
        />
      </label>
      <label>
        Enter your age:
        <input
          type="number"
          name="age"
          value={inputs.age || ""}
          onChange={handleChange}
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyForm />);

5. Textarea

In React, the value of a <textarea> is set using the value attribute instead of placing content between the tags.

Example: Controlled Textarea

import { useState } from "react";
import ReactDOM from "react-dom/client";

function MyForm() {
  const [textarea, setTextarea] = useState("Default content");

  const handleChange = (e) => {
    setTextarea(e.target.value);
  };

  return (
    <form>
      <textarea value={textarea} onChange={handleChange} />
    </form>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyForm />);

6. Select Dropdown

In React, the selected value of a <select> is controlled using the value attribute.

Example: Controlled Select

import { useState } from "react";
import ReactDOM from "react-dom/client";

function MyForm() {
  const [selectedCar, setSelectedCar] = useState("Toyota");

  const handleChange = (e) => {
    setSelectedCar(e.target.value);
  };

  return (
    <form>
      <select value={selectedCar} onChange={handleChange}>
        <option value="Toyota">Toyota</option>
        <option value="Honda">Honda</option>
        <option value="Ford">Ford</option>
      </select>
    </form>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyForm />);

Best Practices

  1. Use Controlled Components: Keep input values in React state for better control.

  2. Dynamic State Updates: Use dynamic property keys (e.g., [name]) for multiple inputs.

  3. Handle Submissions Gracefully: Prevent default behavior and handle data programmatically.


Conclusion

React forms give you fine-grained control over input elements using state and event handlers. Whether you're working with a single input, multiple fields, or complex form elements like <textarea> and <select>, React makes managing form data straightforward.

Try these examples to master form handling in React!


Source Code

The complete source code for this project is available on GitHub


Recent Posts

Latest Posts


logo

Explore insightful articles and tutorials on programming, web development, and mobile app creation. Dive into topics like ReactJS, Next.js, Android, iOS, and modern coding practices. Learn with practical examples and tips for building robust, responsive, and high-performing applications. Perfect for developers of all levels seeking to enhance their skills.

Social

© 2025. All rights reserved