JavaScript and React course · Module 3: State and Events
Forms in React - Controlled Components
In this lesson6
On board the React spaceship, forms are like configuration panels - they serve to input navigation data, set mission parameters, and communicate with command headquarters. In this lesson, you will learn about controlled components - a pattern where React takes full control of form data, just like the onboard computer controls every ship system.
Controlled vs uncontrolled components
In React, we distinguish two approaches to form handling:
Controlled components - React manages the input value through state. Every change goes through useState and onChange:
function ControlledInput() {
const [name, setName] = useState("");
return (
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}Uncontrolled components - the browser manages the value, and we read it via ref:
function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
console.log(inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Send</button>
</form>
);
}Why are controlled components better? Just as the ship's onboard computer must know the state of every system at all times, controlled components give React full visibility into the form data. This allows you to validate, format, and react to changes in real time.
Handling text fields with useState
Simple text input
function PilotRegistration() {
const [pilotName, setPilotName] = useState("");
const [callSign, setCallSign] = useState("");
return (
<div className="registration-form">
<h2>Pilot Registration</h2>
<label>Pilot Name:</label>
<input
type="text"
value={pilotName}
onChange={(e) => setPilotName(e.target.value)}
placeholder="Enter name..."
/>
<label>Call Sign:</label>
<input
type="text"
value={callSign}
onChange={(e) => setCallSign(e.target.value.toUpperCase())}
placeholder="E.g. ALPHA-7"
/>
<p>Pilot: {pilotName} ({callSign})</p>
</div>
);
}Managing multiple fields with a single state
Instead of creating a separate useState for each field, you can use a single state object - like a central mission data registry:
function MissionConfigForm() {
const [formData, setFormData] = useState({
missionName: "",
destination: "",
crewSize: "",
priority: "normal"
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prev) => ({
...prev,
[name]: value
}));
};
return (
<div className="mission-config">
<h2>Mission Configuration</h2>
<label>Mission Name:</label>
<input
type="text"
name="missionName"
value={formData.missionName}
onChange={handleChange}
/>
<label>Destination:</label>
<input
type="text"
name="destination"
value={formData.destination}
onChange={handleChange}
/>
<label>Crew Size:</label>
<input
type="number"
name="crewSize"
value={formData.crewSize}
onChange={handleChange}
/>
<label>Priority:</label>
<input
type="text"
name="priority"
value={formData.priority}
onChange={handleChange}
/>
<pre>{JSON.stringify(formData, null, 2)}</pre>
</div>
);
}The key trick: the name attribute on inputs corresponds to keys in the state object, and [name]: value (computed property name) dynamically updates the corresponding field.
Checkboxes and select elements
Checkbox - system toggles
Checkboxes in React use checked instead of value:
function ShipSystemsPanel() {
const [systems, setSystems] = useState({
engines: true,
shields: false,
weapons: false,
lifeSupport: true
});
const handleToggle = (event) => {
const { name, checked } = event.target;
setSystems((prev) => ({
...prev,
[name]: checked
}));
};
return (
<div className="systems-panel">
<h2>Ship Systems</h2>
<label>
<input
type="checkbox"
name="engines"
checked={systems.engines}
onChange={handleToggle}
/>
Engines
</label>
<label>
<input
type="checkbox"
name="shields"
checked={systems.shields}
onChange={handleToggle}
/>
Shields
</label>
<label>
<input
type="checkbox"
name="weapons"
checked={systems.weapons}
onChange={handleToggle}
/>
Weapon Systems
</label>
<label>
<input
type="checkbox"
name="lifeSupport"
checked={systems.lifeSupport}
onChange={handleToggle}
/>
Life Support
</label>
<div className="status">
Active systems: {Object.entries(systems)
.filter(([, active]) => active)
.map(([name]) => name)
.join(", ")}
</div>
</div>
);
}Select - choosing from a list
The <select> element in React works like other controlled inputs - we control the value through value and onChange:
function NavigationPanel() {
const [destination, setDestination] = useState("");
const [warpSpeed, setWarpSpeed] = useState("1");
const destinations = [
{ value: "mars", label: "Mars" },
{ value: "jupiter", label: "Jupiter" },
{ value: "saturn", label: "Saturn" },
{ value: "alpha-centauri", label: "Alpha Centauri" },
{ value: "andromeda", label: "Andromeda Galaxy" }
];
return (
<div className="nav-panel">
<h2>Navigation Panel</h2>
<label>Destination:</label>
<select
value={destination}
onChange={(e) => setDestination(e.target.value)}
>
<option value="">-- Select destination --</option>
{destinations.map((dest) => (
<option key={dest.value} value={dest.value}>
{dest.label}
</option>
))}
</select>
<label>Warp Speed:</label>
<select
value={warpSpeed}
onChange={(e) => setWarpSpeed(e.target.value)}
>
<option value="1">Warp 1</option>
<option value="3">Warp 3</option>
<option value="5">Warp 5</option>
<option value="9">Warp 9 (maximum)</option>
</select>
{destination && (
<p>Course set: {destination} at Warp {warpSpeed}</p>
)}
</div>
);
}Handling form submission
Submitting a form is like issuing an order from command headquarters - it must be controlled and secure:
function MissionReportForm() {
const [formData, setFormData] = useState({
missionName: "",
commander: "",
status: "in-progress",
description: "",
isClassified: false
});
const [submitted, setSubmitted] = useState(false);
const handleChange = (event) => {
const { name, value, type, checked } = event.target;
setFormData((prev) => ({
...prev,
[name]: type === "checkbox" ? checked : value
}));
};
const handleSubmit = (event) => {
event.preventDefault();
// Validation
if (!formData.missionName.trim() || !formData.commander.trim()) {
alert("Please fill in all required fields!");
return;
}
console.log("Mission report:", formData);
setSubmitted(true);
};
const handleReset = () => {
setFormData({
missionName: "",
commander: "",
status: "in-progress",
description: "",
isClassified: false
});
setSubmitted(false);
};
if (submitted) {
return (
<div className="success">
<h2>Report Submitted!</h2>
<p>Mission: {formData.missionName}</p>
<button onClick={handleReset}>New Report</button>
</div>
);
}
return (
<form onSubmit={handleSubmit} className="mission-report">
<h2>Mission Report</h2>
<label>Mission Name *:</label>
<input
type="text"
name="missionName"
value={formData.missionName}
onChange={handleChange}
required
/>
<label>Commander *:</label>
<input
type="text"
name="commander"
value={formData.commander}
onChange={handleChange}
required
/>
<label>Status:</label>
<select name="status" value={formData.status} onChange={handleChange}>
<option value="in-progress">In Progress</option>
<option value="completed">Completed</option>
<option value="failed">Failed</option>
</select>
<label>Description:</label>
<textarea
name="description"
value={formData.description}
onChange={handleChange}
rows={4}
placeholder="Describe the mission progress..."
/>
<label>
<input
type="checkbox"
name="isClassified"
checked={formData.isClassified}
onChange={handleChange}
/>
Classified Report
</label>
<div className="form-actions">
<button type="submit">Submit Report</button>
<button type="button" onClick={handleReset}>Clear</button>
</div>
</form>
);
}Lifting state up
When multiple components need to share form data, we move the state to their common parent - like a command center coordinating data from multiple panels:
function TemperatureInput({ label, value, onChange }) {
return (
<div>
<label>{label}:</label>
<input
type="number"
value={value}
onChange={(e) => onChange(e.target.value)}
/>
</div>
);
}
function TemperatureConverter() {
// The parent only remembers what was typed last, and in which scale
const [temperature, setTemperature] = useState({ scale: "c", value: "" });
const convert = (value, formula) => {
const number = parseFloat(value);
return Number.isNaN(number) ? "" : String(Math.round(formula(number) * 100) / 100);
};
const celsius = temperature.scale === "f"
? convert(temperature.value, (f) => ((f - 32) * 5) / 9)
: temperature.value;
const fahrenheit = temperature.scale === "c"
? convert(temperature.value, (c) => (c * 9) / 5 + 32)
: temperature.value;
return (
<div className="converter">
<h2>Hull Temperature Converter</h2>
<TemperatureInput
label="Celsius"
value={celsius}
onChange={(value) => setTemperature({ scale: "c", value })}
/>
<TemperatureInput
label="Fahrenheit"
value={fahrenheit}
onChange={(value) => setTemperature({ scale: "f", value })}
/>
</div>
);
}In this pattern:
- The state (
temperature: the last typed value and its scale) lives in the parent (TemperatureConverter) - The child components (
TemperatureInput) receive the value via props - Changes are passed upward through the
onChangecallback - The parent recalculates and synchronizes both values
The parent does not store ready-made degrees Celsius, but the last typed value and its scale. That way the field you are typing in shows exactly what you type (even a lone - or 10), and the other field is converted and rounded to two decimal places.
Summary
Forms in React - key principles:
- Controlled components - React manages input values through
value+onChange - Single state for multiple fields - use a state object with dynamic
[name]: value - Checkboxes - use
checkedinstead ofvalue, readevent.target.checked - Select - control via
valueon<select>, not on<option> - preventDefault() - always block the default form submission
- Validation - check data in the
onSubmithandler before submitting - Lifting state up - move state to a common parent when components need to share data
Code for this lesson: App.jsx
import React, { useState } from 'react';
function SpaceMissionForm() {
const [formData, setFormData] = useState({
missionName: '',
destination: 'mars',
crewSize: 4,
duration: '',
priority: 'medium',
equipment: [],
notes: '',
launchDate: '',
isUrgent: false
});
const [errors, setErrors] = useState({});
const [submitted, setSubmitted] = useState(false);
const equipmentOptions = [
{ id: 'rover', label: 'Rover' },
{ id: 'drone', label: 'Drone' },
{ id: 'satellite', label: 'Satellite' },
{ id: 'telescope', label: 'Telescope' },
{ id: 'lab', label: 'Laboratory' }
];
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setFormData(prev => ({
...prev,
[name]: type === 'checkbox' ? checked : value
}));
if (errors[name]) {
setErrors(prev => ({ ...prev, [name]: null }));
}
};
const handleEquipmentChange = (id) => {
setFormData(prev => ({
...prev,
equipment: prev.equipment.includes(id)
? prev.equipment.filter(e => e !== id)
: [...prev.equipment, id]
}));
};
const validate = () => {
const newErrors = {};
if (!formData.missionName.trim()) newErrors.missionName = 'Mission name is required';
if (!formData.duration || formData.duration < 1) newErrors.duration = 'Duration must be greater than 0';
if (!formData.launchDate) newErrors.launchDate = 'Launch date is required';
if (formData.equipment.length === 0) newErrors.equipment = 'Select at least one piece of equipment';
return newErrors;
};
const handleSubmit = (e) => {
e.preventDefault();
const newErrors = validate();
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return;
}
setSubmitted(true);
console.log('Submitted:', formData);
};
const handleReset = () => {
setFormData({
missionName: '', destination: 'mars', crewSize: 4, duration: '',
priority: 'medium', equipment: [], notes: '', launchDate: '', isUrgent: false
});
setErrors({});
setSubmitted(false);
};
if (submitted) {
return (
<div style={{ fontFamily: 'Arial', padding: '40px', textAlign: 'center' }}>
<div style={{ fontSize: '64px', marginBottom: '20px' }}>▲</div>
<h1 style={{ color: '#4caf50' }}>Mission scheduled!</h1>
<div style={{ backgroundColor: '#f5f5f5', padding: '20px', borderRadius: '12px', maxWidth: '500px', margin: '20px auto', textAlign: 'left' }}>
<p><strong>Name:</strong> {formData.missionName}</p>
<p><strong>Destination:</strong> {formData.destination}</p>
<p><strong>Crew:</strong> {formData.crewSize} people</p>
<p><strong>Duration:</strong> {formData.duration} days</p>
<p><strong>Launch date:</strong> {formData.launchDate}</p>
<p><strong>Equipment:</strong> {formData.equipment.join(', ')}</p>
</div>
<button onClick={handleReset} style={{ padding: '12px 24px', backgroundColor: '#667eea', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer' }}>
Schedule a new mission
</button>
</div>
);
}
return (
<div style={{ fontFamily: 'Arial', padding: '20px', maxWidth: '600px', margin: '0 auto' }}>
<h1 style={{ textAlign: 'center', color: '#667eea' }}>Space Mission Planning</h1>
<form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
<div>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Mission name *</label>
<input type="text" name="missionName" value={formData.missionName} onChange={handleChange}
style={{ width: '100%', padding: '10px', borderRadius: '8px', border: errors.missionName ? '2px solid #f44336' : '1px solid #ddd', boxSizing: 'border-box' }}
/>
{errors.missionName && <span style={{ color: '#f44336', fontSize: '12px' }}>{errors.missionName}</span>}
</div>
<div>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Travel destination</label>
<select name="destination" value={formData.destination} onChange={handleChange}
style={{ width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd' }}>
<option value="mars">Mars</option>
<option value="moon">Moon</option>
<option value="venus">Venus</option>
<option value="jupiter">Jupiter</option>
<option value="saturn">Saturn</option>
</select>
</div>
<div>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Crew size: {formData.crewSize}</label>
<input type="range" name="crewSize" min="1" max="20" value={formData.crewSize} onChange={handleChange}
style={{ width: '100%' }}
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Duration (days) *</label>
<input type="number" name="duration" value={formData.duration} onChange={handleChange}
style={{ width: '100%', padding: '10px', borderRadius: '8px', border: errors.duration ? '2px solid #f44336' : '1px solid #ddd', boxSizing: 'border-box' }}
/>
{errors.duration && <span style={{ color: '#f44336', fontSize: '12px' }}>{errors.duration}</span>}
</div>
<div>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Launch date *</label>
<input type="date" name="launchDate" value={formData.launchDate} onChange={handleChange}
style={{ width: '100%', padding: '10px', borderRadius: '8px', border: errors.launchDate ? '2px solid #f44336' : '1px solid #ddd', boxSizing: 'border-box' }}
/>
{errors.launchDate && <span style={{ color: '#f44336', fontSize: '12px' }}>{errors.launchDate}</span>}
</div>
<div>
<label style={{ display: 'block', marginBottom: '10px', fontWeight: 'bold' }}>Priority</label>
<div style={{ display: 'flex', gap: '20px' }}>
{['low', 'medium', 'high'].map(p => (
<label key={p} style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<input type="radio" name="priority" value={p} checked={formData.priority === p} onChange={handleChange} />
{p === 'low' ? 'Low' : p === 'medium' ? 'Medium' : 'High'}
</label>
))}
</div>
</div>
<div>
<label style={{ display: 'block', marginBottom: '10px', fontWeight: 'bold' }}>Equipment *</label>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px' }}>
{equipmentOptions.map(eq => (
<label key={eq.id} style={{
padding: '8px 16px', borderRadius: '20px', cursor: 'pointer',
backgroundColor: formData.equipment.includes(eq.id) ? '#667eea' : '#e0e0e0',
color: formData.equipment.includes(eq.id) ? 'white' : '#333'
}}>
<input type="checkbox" checked={formData.equipment.includes(eq.id)}
onChange={() => handleEquipmentChange(eq.id)} style={{ display: 'none' }}
/>
{eq.label}
</label>
))}
</div>
{errors.equipment && <span style={{ color: '#f44336', fontSize: '12px' }}>{errors.equipment}</span>}
</div>
<div>
<label style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer' }}>
<input type="checkbox" name="isUrgent" checked={formData.isUrgent} onChange={handleChange} />
<span style={{ fontWeight: 'bold' }}>Urgent mission</span>
</label>
</div>
<div>
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Notes</label>
<textarea name="notes" value={formData.notes} onChange={handleChange} rows="3"
style={{ width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', boxSizing: 'border-box', resize: 'vertical' }}
/>
</div>
<div style={{ display: 'flex', gap: '10px' }}>
<button type="submit" style={{ flex: 1, padding: '12px', backgroundColor: '#4caf50', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer', fontWeight: 'bold' }}>
Schedule mission
</button>
<button type="button" onClick={handleReset} style={{ flex: 1, padding: '12px', backgroundColor: '#f44336', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer', fontWeight: 'bold' }}>
Clear
</button>
</div>
</form>
</div>
);
}
export default function App() {
return <SpaceMissionForm />;
}Remember: Controlled components are like the ship's control system - the onboard computer (React) knows about every change in real time and can react immediately!
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Can you use multiple useState hooks in a single component?
2. What is the difference between state and props?
These are 2 of 9 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Click in order
Build an onSubmit handler that prevents page reload:
- Vertical ordering
Arrange the steps for creating a controlled form in React:
- Code editor
Create an EmergencyAlert component with a message state shown in a <p> paragraph and render it in App. Add an ALARM button: onClick sets the message 'Alarm activated!' and onMouseEnter sets 'Careful: cursor over the alarm button'. Also add an <input> field with onKeyDown that sets 'Alarm triggered from the keyboard' when Enter is pressed (e.key === 'Enter') and ignores other keys.
- Code editor
Create a parent ColonyControl with a powerLevel state (useState(50)) and two children without their own state: PowerPlant({ powerLevel, onPowerChange }) shows the power level and has +10 and -10 buttons that call onPowerChange with the new value, and LifeSupport({ powerLevel }), which shows 'Life support: active' when powerLevel >= 30 and 'ALARM: not enough power' otherwise. ColonyControl passes the same powerLevel to both children. Render ColonyControl in App.
- Code editor
Create a ColonyDashboard component with four separate useState states: temperature (e.g. -20), pressure (e.g. 600), oxygen (e.g. 21) and power (e.g. 80), and render it in App. Display all four values and, for each of them, add a button that changes only that value (e.g. Heat +5, Pressure +10, Oxygen +1, Power -10).
- Click in order
Build the expression that retrieves the value from an input field in an event handler:
- Horizontal ordering
Arrange the syntax for importing the useState hook from React:
- Click in order
Arrange the event handling flow:
- Vertical ordering
Arrange the ways of keeping state from the simplest to the most elaborate, as in the lesson on data flow:
- Vertical ordering
Arrange what happens after typing one character into the controlled field <input value={name} onChange={(e) => setName(e.target.value)} />:
- Click in order
Arrange the state update process:
- Horizontal ordering
Arrange the correct onChange attribute for a controlled input:
- Click in order
Click the elements in order to create a controlled input with onChange:
- Vertical ordering
Arrange the steps of the React state update cycle from event to DOM update:
- Horizontal ordering
Arrange the correct way to update a single property of an object in useState:
- Vertical ordering
Arrange the validation steps of the MissionPlanner form from the lesson on event handling:
Tasks after this lesson
- Click in orderonSubmit Handler with preventDefault
- QuestionMultiple State Variables
- Put in orderSteps to Build a Controlled Form
- Coding taskPractice: onClick, onMouseEnter and onKeyDown
- QuestionState vs Props
- Coding taskPractice: Lifting State Up
- QuestionLifting State Up
- Coding taskPractice: Multiple States
- QuestiononClick Event Handler
- Click in orderAccessing Input Value Through an Event
- QuestionControlled vs Uncontrolled Components
- Put in orderImporting the useState Hook
- Click in orderSorting: Event Handling Flow
- Put in orderState Management Patterns
- Put in orderControlled Input Cycle
- Click in orderSorting: State Update Process
- QuestionAsynchronous State Updates
- Put in orderonChange Syntax for a Controlled Input
- QuestionAdvantages of Controlled Components
- QuestionuseState Initialization
- QuestionLifting State Up Pattern
- Click in orderControlled Input Syntax
- Put in orderReact State Update Cycle
- Put in orderUpdating an Object with the Spread Operator
- Put in orderForm Validation Step by Step