Chapter 9: Forms in React
Almost every real app has forms: login, signup, search, comments, checkout, contact us… you name it. Today we’ll learn how to handle forms the React way — correctly, efficiently, and in a way that feels natural.
We’ll go slowly and clearly, like I’m sitting next to you in Mumbai showing you live on the screen.
1. Controlled vs Uncontrolled Components (The Big Decision)
| Feature | Controlled Components (Recommended 99% of the time) | Uncontrolled Components (Rarely used) |
|---|---|---|
| State | React controls the value via state | The DOM controls the value |
| Value | value={state} + onChange to update state | No value, use defaultValue |
| Access value | Always know the current value in React state | Need ref to read value when needed |
| Validation | Easy — validate in state | Harder — read value on submit |
| Instant feedback | Real-time validation, formatting, etc. | Only on submit |
| When to use | Almost everything: login, search, todo add, etc. | Very simple forms, legacy code, or file inputs |
Official React recommendation in 2026: Use controlled components for most forms. They give you full control, make validation easy, and keep everything in sync with React state.
2. Handling Common Form Inputs (Controlled Way)
Let’s build a beautiful, complete registration form that handles:
- Text input
- Password
- Textarea
- Select (dropdown)
- Checkbox
- Radio buttons
Create new file: src/components/RegistrationForm.tsx
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
import { useState, FormEvent } from 'react'; function RegistrationForm() { // All form fields in one state object (very common pattern) const [formData, setFormData] = useState({ fullName: '', email: '', password: '', bio: '', country: 'India', // default value newsletter: false, gender: 'male' // default radio selection }); const [submitted, setSubmitted] = useState(false); // Single handler for ALL inputs (clean!) const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => { const { name, value, type } = e.target; const checked = (e.target as HTMLInputElement).checked; // for checkboxes setFormData(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value })); }; const handleSubmit = (e: FormEvent) => { e.preventDefault(); // ← stops page reload! // Simple validation example if (!formData.fullName || !formData.email || !formData.password) { alert('Please fill all required fields!'); return; } // In real app → send to backend console.log('Form submitted:', formData); setSubmitted(true); }; return ( <div style={{ maxWidth: '600px', margin: '40px auto', padding: '40px', background: '#f8f9ff', borderRadius: '16px', boxShadow: '0 8px 30px rgba(0,0,0,0.1)' }}> <h2 style={{ color: '#646cff', textAlign: 'center', marginBottom: '30px' }}> Registration Form </h2> {submitted ? ( <div style={{ textAlign: 'center', color: '#4ecdc4', fontSize: '22px', padding: '40px 0' }}> 🎉 Thank you, {formData.fullName}! Registration successful! </div> ) : ( <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}> {/* Text input */} <div> <label htmlFor="fullName" style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}> Full Name * </label> <input type="text" id="fullName" name="fullName" value={formData.fullName} onChange={handleChange} placeholder="John Doe" required style={{ width: '100%', padding: '12px', borderRadius: '8px', border: '1px solid #ddd' }} /> </div> {/* Email */} <div> <label htmlFor="email">Email *</label> <input type="email" id="email" name="email" value={formData.email} onChange={handleChange} placeholder="you@example.com" required style={{ width: '100%', padding: '12px', borderRadius: '8px', border: '1px solid #ddd' }} /> </div> {/* Password */} <div> <label htmlFor="password">Password *</label> <input type="password" id="password" name="password" value={formData.password} onChange={handleChange} placeholder="••••••••" required style={{ width: '100%', padding: '12px', borderRadius: '8px', border: '1px solid #ddd' }} /> </div> {/* Textarea */} <div> <label htmlFor="bio">Short Bio</label> <textarea id="bio" name="bio" value={formData.bio} onChange={handleChange} placeholder="Tell us a little about yourself..." rows={4} style={{ width: '100%', padding: '12px', borderRadius: '8px', border: '1px solid #ddd' }} /> </div> {/* Select (Dropdown) */} <div> <label htmlFor="country">Country</label> <select id="country" name="country" value={formData.country} onChange={handleChange} style={{ width: '100%', padding: '12px', borderRadius: '8px', border: '1px solid #ddd' }} > <option value="India">India</option> <option value="USA">USA</option> <option value="UK">UK</option> <option value="Canada">Canada</option> <option value="Australia">Australia</option> </select> </div> {/* Checkbox */} <div> <label style={{ display: 'flex', alignItems: 'center', gap: '10px' }}> <input type="checkbox" name="newsletter" checked={formData.newsletter} onChange={handleChange} /> Subscribe to our newsletter </label> </div> {/* Radio Buttons */} <div> <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>Gender</label> <div style={{ display: 'flex', gap: '30px' }}> <label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <input type="radio" name="gender" value="male" checked={formData.gender === 'male'} onChange={handleChange} /> Male </label> <label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <input type="radio" name="gender" value="female" checked={formData.gender === 'female'} onChange={handleChange} /> Female </label> <label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <input type="radio" name="gender" value="other" checked={formData.gender === 'other'} onChange={handleChange} /> Other </label> </div> </div> {/* Submit Button */} <button type="submit" style={{ padding: '14px', fontSize: '18px', backgroundColor: '#646cff', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer', marginTop: '20px' }} > Register </button> </form> )} </div> ); } export default RegistrationForm; |
Use in App.tsx:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import RegistrationForm from './components/RegistrationForm'; function App() { return ( <div> <h1 style={{ textAlign: 'center', color: '#646cff', margin: '40px 0' }}> Chapter 9: Forms in React </h1> <RegistrationForm /> </div> ); } |
3. Form Submission – Summary of Best Practices
- Always use e.preventDefault() in onSubmit
- Use controlled inputs → value + onChange
- Use one state object for the whole form (or separate states — both fine)
- Use single handleChange function with name attribute
- Validate on submit (or better — real-time validation)
- Show success/error messages after submit
- Disable button while submitting (in real apps)
Summary – Chapter 9 Key Takeaways
- Controlled components = React state controls input value → best for most cases
- Use value={state} + onChange={updateState}
- Use one handler for all inputs by using name attribute
- textarea, select, checkbox, radio work almost the same way
- Always e.preventDefault() on form submit
- Real-time validation & feedback = great user experience
Mini Homework
- Add real-time validation:
- Show red border + error message if email is invalid
- Show password strength indicator
- Bonus: Add a “Confirm Password” field and check if it matches
