React Forms

Handling user input in React applications

📝 What are React Forms?

React forms handle user input through controlled components. By storing form values in state and updating them with onChange handlers, React maintains full control over form data, making validation and submission easy.


function SimpleForm() {
  const [name, setName] = useState('');
  
  return (
    <input 
      type="text" 
      value={name}
      onChange={(e) => setName(e.target.value)}
      placeholder="Enter your name"
    />
  );
}
                                    

Output:

Form Concepts

🎛️

Controlled Components

React controls input values

value={state}
onChange={handler}
📊

State Management

Store form data in state

const [value, setValue] = 
  useState('');
🔄

Event Handlers

Update state on change

onChange={(e) => 
  setValue(e.target.value)}

Validation

Check input before submit

if (value.length < 3) {
  setError('Too short');
}

🔹 Basic Input Field

A controlled input field in React uses state to store the current value and an onChange handler to update it. This gives you complete control over the input's behavior and value.

import { useState } from 'react';

function NameForm() {
  const [name, setName] = useState('');
  
  return (
    <div>
      <label>
        Name:
        <input 
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <p>Hello, {name}!</p>
    </div>
  );
}

Output:

Hello, [your input]!

🔹 Multiple Input Fields

When handling multiple inputs, you can use a single state object to store all form values. This keeps your code organized and makes it easier to manage complex forms with many fields.

function ContactForm() {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: ''
  });
  
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  return (
    <form>
      <input 
        name="firstName"
        value={formData.firstName}
        onChange={handleChange}
        placeholder="First Name"
      />
      <input 
        name="lastName"
        value={formData.lastName}
        onChange={handleChange}
        placeholder="Last Name"
      />
      <input 
        name="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Email"
      />
    </form>
  );
}

Output:

🔹 Checkbox Input

Checkboxes work differently from text inputs. Instead of using the value property, you use the checked property and access e.target.checked in the onChange handler to get the boolean state.

function SubscribeForm() {
  const [isSubscribed, setIsSubscribed] = useState(false);
  
  return (
    <div>
      <label>
        <input 
          type="checkbox"
          checked={isSubscribed}
          onChange={(e) => setIsSubscribed(e.target.checked)}
        />
        Subscribe to newsletter
      </label>
      <p>{isSubscribed ? 'Subscribed!' : 'Not subscribed'}</p>
    </div>
  );
}

Output:

Not subscribed

🔹 Radio Buttons

Radio buttons allow users to select one option from multiple choices. All radio buttons in a group share the same name attribute, and you check which one is selected by comparing values.

function SizeSelector() {
  const [size, setSize] = useState('medium');
  
  return (
    <div>
      <label>
        <input 
          type="radio"
          value="small"
          checked={size === 'small'}
          onChange={(e) => setSize(e.target.value)}
        />
        Small
      </label>
      <label>
        <input 
          type="radio"
          value="medium"
          checked={size === 'medium'}
          onChange={(e) => setSize(e.target.value)}
        />
        Medium
      </label>
      <label>
        <input 
          type="radio"
          value="large"
          checked={size === 'large'}
          onChange={(e) => setSize(e.target.value)}
        />
        Large
      </label>
      <p>Selected: {size}</p>
    </div>
  );
}

Output:

Selected: medium

🧠 Test Your Knowledge

What makes an input a "controlled component" in React?