⚛️ React Forms

Chapter 9 of 15

React Forms

Just like in HTML, React uses forms to allow users to interact with the web page. However, in React, form data is usually handled by the components themselves.

💡 Controlled Components: In React, form inputs whose values are controlled by React state are called "controlled components".

Adding a Form

You add a form with React like any other element:

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

Handling Forms

In React, we control form data by storing it in component state. You can control changes by adding event handlers in the onChange attribute:

import { useState } from 'react';

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>
  )
}
✨ Two-Way Binding: The input value is bound to state, and state is updated when the input changes. This creates a "single source of truth"!

Submitting Forms

You can control the submit action by adding an event handler in the onSubmit attribute:

import { useState } from 'react';

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

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was: ${name}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Enter your name:
        <input 
          type="text" 
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <input type="submit" />
    </form>
  )
}
⚠️ Remember: Always use event.preventDefault() to prevent the page from refreshing when the form is submitted!

Multiple Input Fields

You can control multiple input fields by adding a name attribute to each element and using one handler:

import { useState } from 'react';

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

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

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(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>
      <input type="submit" />
    </form>
  )
}

Textarea

The textarea element in React is slightly different from HTML. In React, the value is handled by a value attribute:

import { useState } from 'react';

function MyForm() {
  const [textarea, setTextarea] = useState(
    "The content of a textarea goes in the value attribute"
  );

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

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

Select

In React, the selected value in a drop down list is defined with a value attribute on the select tag:

import { useState } from 'react';

function MyForm() {
  const [myCar, setMyCar] = useState("Volvo");

  const handleChange = (event) => {
    setMyCar(event.target.value);
  }

  return (
    <form>
      <select value={myCar} onChange={handleChange}>
        <option value="Ford">Ford</option>
        <option value="Volvo">Volvo</option>
        <option value="Fiat">Fiat</option>
      </select>
    </form>
  )
}

Checkboxes

Checkboxes use the checked attribute instead of value:

import { useState } from 'react';

function MyForm() {
  const [isChecked, setIsChecked] = useState(false);

  const handleChange = (event) => {
    setIsChecked(event.target.checked);
  }

  return (
    <form>
      <label>
        <input
          type="checkbox"
          checked={isChecked}
          onChange={handleChange}
        />
        I agree to the terms
      </label>
      <p>{isChecked ? "Agreed" : "Not agreed"}</p>
    </form>
  )
}

Radio Buttons

Radio buttons are similar to other inputs:

import { useState } from 'react';

function MyForm() {
  const [gender, setGender] = useState("male");

  const handleChange = (event) => {
    setGender(event.target.value);
  }

  return (
    <form>
      <label>
        <input
          type="radio"
          value="male"
          checked={gender === "male"}
          onChange={handleChange}
        />
        Male
      </label>
      <label>
        <input
          type="radio"
          value="female"
          checked={gender === "female"}
          onChange={handleChange}
        />
        Female
      </label>
    </form>
  )
}

Form Validation

You can add validation to your forms:

import { useState } from 'react';

function MyForm() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    
    if (!email.includes("@")) {
      setError("Please enter a valid email");
      return;
    }
    
    setError("");
    alert("Form submitted successfully!");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Enter email"
      />
      {error && <p style={{color: "red"}}>{error}</p>}
      <button type="submit">Submit</button>
    </form>
  )
}

Complete Registration Form Example

import { useState } from 'react';

function RegistrationForm() {
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    password: "",
    country: "USA",
    agreeTerms: false
  });

  const handleChange = (event) => {
    const { name, value, type, checked } = event.target;
    setFormData(prevData => ({
      ...prevData,
      [name]: type === "checkbox" ? checked : value
    }));
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log("Form Data:", formData);
  }

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

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

      <div>
        <label>Password:</label>
        <input
          type="password"
          name="password"
          value={formData.password}
          onChange={handleChange}
          required
        />
      </div>

      <div>
        <label>Country:</label>
        <select
          name="country"
          value={formData.country}
          onChange={handleChange}
        >
          <option value="USA">USA</option>
          <option value="Canada">Canada</option>
          <option value="UK">UK</option>
        </select>
      </div>

      <div>
        <label>
          <input
            type="checkbox"
            name="agreeTerms"
            checked={formData.agreeTerms}
            onChange={handleChange}
            required
          />
          I agree to the terms and conditions
        </label>
      </div>

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

Uncontrolled Components

Sometimes you might want to use uncontrolled components with refs instead of state:

import { useRef } from 'react';

function MyForm() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert("Input value: " + inputRef.current.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  )
}
💡 Controlled vs Uncontrolled: Controlled components (using state) are recommended in most cases as they give you more control and are easier to test.

Form Best Practices

What's Next?

Now that you understand forms, you're ready to learn about React Router - how to add navigation and routing to your React applications!