React Forms
Forms are how users give your app data. React supports two styles: controlled inputs, where React state holds the current value, and uncontrolled inputs, where the DOM keeps the value and you read it when needed (for example on submit).
Controlled inputs
A controlled input gets its value from state and reports every change through onChange. State is the single source of truth, so you can validate, transform or display the value as the user types:
import { useState } from 'react';
export default function App() {
const [name, setName] = useState('');
return (
<div>
<label>
Username:{' '}
<input value={name} onChange={(e) => setName(e.target.value.toLowerCase().replace(/\s/g, ''))} />
</label>
<p>Your profile URL: example.com/@{name || '…'}</p>
<p>{name.length}/15 characters {name.length > 15 && <strong style={{ color: 'crimson' }}>— too long!</strong>}</p>
</div>
);
}The input forces lowercase and strips spaces — possible only because every keystroke flows through your code.
Note: If you give an input a
valuebut noonChange, it becomes read-only and React warns you. UsedefaultValuefor an uncontrolled input with an initial value.
Handling a whole form
With several fields, keep one state object and a single change handler that uses the input's name:
import { useState } from 'react';
export default function App() {
const [form, setForm] = useState({ email: '', plan: 'free', newsletter: true, bio: '' });
const [submitted, setSubmitted] = useState(null);
function handleChange(e) {
const { name, type, value, checked } = e.target;
setForm({ ...form, [name]: type === 'checkbox' ? checked : value });
}
function handleSubmit(e) {
e.preventDefault();
setSubmitted(form);
}
return (
<form onSubmit={handleSubmit} style={{ display: 'grid', gap: 8, maxWidth: 320 }}>
<input name="email" type="email" placeholder="Email" value={form.email} onChange={handleChange} required />
<select name="plan" value={form.plan} onChange={handleChange}>
<option value="free">Free</option>
<option value="pro">Pro — $5/month</option>
<option value="team">Team — $20/month</option>
</select>
<textarea name="bio" rows={3} placeholder="Short bio" value={form.bio} onChange={handleChange} />
<label>
<input name="newsletter" type="checkbox" checked={form.newsletter} onChange={handleChange} /> Send me the newsletter
</label>
<button type="submit">Sign up</button>
{submitted && <pre style={{ background: '#f4f4f4', padding: 8 }}>{JSON.stringify(submitted, null, 2)}</pre>}
</form>
);
}[name]: value is a computed property name: it sets the key whose name is stored in the name variable.
Form elements in React
| Element | Value prop | Change event reads |
|---|---|---|
<input type="text"> |
value |
e.target.value |
<textarea> |
value (not children!) |
e.target.value |
<select> |
value on the <select> |
e.target.value |
<input type="checkbox"> |
checked |
e.target.checked |
<input type="radio"> |
checked |
compare e.target.value |
<input type="number"> |
value |
e.target.value (a string! use Number()) |
Radio buttons
import { useState } from 'react';
const SIZES = ['S', 'M', 'L', 'XL'];
export default function App() {
const [size, setSize] = useState('M');
return (
<fieldset style={{ width: 260 }}>
<legend>T-shirt size</legend>
{SIZES.map((s) => (
<label key={s} style={{ marginRight: 10 }}>
<input type="radio" name="size" value={s} checked={size === s} onChange={(e) => setSize(e.target.value)} /> {s}
</label>
))}
<p>Selected: <strong>{size}</strong></p>
</fieldset>
);
}Validation
Because values live in state, validation is ordinary JavaScript computed during rendering:
import { useState } from 'react';
export default function App() {
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const checks = [
{ ok: password.length >= 8, text: 'At least 8 characters' },
{ ok: /[A-Z]/.test(password), text: 'An uppercase letter' },
{ ok: /\d/.test(password), text: 'A number' },
{ ok: password !== '' && password === confirm, text: 'Both passwords match' },
];
const valid = checks.every((c) => c.ok);
return (
<form onSubmit={(e) => { e.preventDefault(); console.log('Password accepted'); }}>
<input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />{' '}
<input type="password" placeholder="Confirm" value={confirm} onChange={(e) => setConfirm(e.target.value)} />
<ul style={{ listStyle: 'none', padding: 0 }}>
{checks.map((c) => (
<li key={c.text} style={{ color: c.ok ? 'green' : 'gray' }}>{c.ok ? '✔' : '○'} {c.text}</li>
))}
</ul>
<button disabled={!valid}>Create account</button>
</form>
);
}Uncontrolled forms with FormData
For simple forms you don't always need state for every field. Give inputs a name, and read all values on submit with the browser's FormData:
import { useState } from 'react';
export default function App() {
const [message, setMessage] = useState('');
function handleSubmit(e) {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.currentTarget));
setMessage(`Booked a table for ${data.guests} on ${data.date || '(no date)'} under "${data.name}".`);
e.currentTarget.reset();
}
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Name" defaultValue="Tran" />{' '}
<input name="guests" type="number" min="1" defaultValue="2" style={{ width: 60 }} />{' '}
<input name="date" type="date" />{' '}
<button>Book</button>
<p>{message}</p>
</form>
);
}Tip: React 19 also lets you pass a function directly to
<form action={…}>, which receives theFormDataand works with pending states. You'll learn it in the React 19 Actions lesson.
| Choose… | When |
|---|---|
| Controlled | you need live validation, formatting, or dependent fields |
| Uncontrolled + FormData | you only need the values on submit |
Test yourself
What makes an input 'controlled'?
- It has a name attribute
- Its value comes from React state and changes go through onChange
- It is inside a <form>
- It uses defaultValue
Which property holds a checkbox's state in the change event?
- e.target.value
- e.target.checked
- e.checked
- e.target.selected
What type is e.target.value for <input type="number">?
- number
- string
- bigint
- It depends on the browser