You fill in a sign-up form, press Send, and the page flickers: everything you typed is gone. Or you build a field in React, type into it, and the letters don't appear at all. Both problems are common in a first React form, and this lesson covers both.
In React, an input is usually controlled by state: what's in it is read from state, and every keystroke is written back to state through onChange. This pattern is called a controlled component. It's like the order screen at a fast food counter. You say your order, the cashier types it into the cash register, and the screen facing you only shows what the register has recorded. If the cashier doesn't type it in, the screen doesn't change, however loudly you say your order. In React, the order you say is your typing, the register's record is the state, the screen is the input, and the cashier is onChange.
Controlled input: value and onChange
This component has one email field, and below it a preview that shows what's in that field:
function App() {
const [email, setEmail] = useState("")
return (
<div>
<input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<p id="preview">{email}</p>
</div>
)
}
useState(""): the starting value is an empty string, because the field starts empty.value={email}: what's in the field is read from state. The direction is state to screen.onChange={(e) => setEmail(e.target.value)}: on every keystroke, React callsonChangewith an event objecte.e.targetis the field, ande.target.valueis what's in it right now, the new letter included. The direction is keystroke to state.<p id="preview">{email}</p>reads the same state, so it changes with every keystroke.
This is what happens when you type rin:
| Keystroke | e.target.value |
Called | email in the next render |
Field and preview |
|---|---|---|---|---|
| r | "r" |
setEmail("r") |
"r" |
r |
| i | "ri" |
setEmail("ri") |
"ri" |
ri |
| n | "rin" |
setEmail("rin") |
"rin" |
rin |
Without onChange, your typing never reaches the state. value stays "", and on every render React writes the field back to empty. So the field stays empty, like a screen whose cashier records nothing. React also warns in the console that the field has become read-only (it can only be read).
Forms: onSubmit and preventDefault
This login form has two fields and one button. When the form is sent, what's in the username field is printed to the console:
function App() {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const handleSubmit = (e) => {
e.preventDefault() // stop the browser from reloading the page
console.log(username) // prints what's in the field right now, e.g. Budi
}
return (
<form onSubmit={handleSubmit}>
<input id="username" value={username} onChange={(e) => setUsername(e.target.value)} />
<input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button id="submit" type="submit">Login</button>
</form>
)
}
- Each field has its own state,
usernameandpassword, and both are controlled. onSubmitgoes on the<form>, not on the button. The form is sent by clicking atype="submit"button or by pressing Enter in a field, and both triggeronSubmit. The button has to be inside the<form>.- The browser's built-in action when a form is sent is to reload the page. All state is lost, and the console output is cleared too.
e.preventDefault()cancels that built-in action. console.log(username)reads the state, so what it prints is whatever is in the field right now.
Type Budi, then press Login: the console prints Budi, and the page doesn't reload.
React 19 has another way: <form action={fn}>. React calls that function with the form's content as FormData (an object that holds what's in every field of the form), with no need for e.preventDefault(). The Advanced Forms lesson covers this way.
Controlled or uncontrolled
A field with no value is called uncontrolled: the browser keeps what's in it, not state.
| Controlled | Uncontrolled | |
|---|---|---|
| What's in the field lives in | React state | the browser |
| Written as | value={x} and onChange |
no value (defaultValue for the starting contents is allowed) |
| Can be emptied from code | yes, setX("") |
not directly |
| Usable while typing | yes, read directly from state | only through events |
Use controlled in two situations:
- What's in the field is used while it's being typed, for example for a preview, for checking a password's length, or for a button that only becomes active when the form is complete.
- The field has to be emptied after the form is sent.
In the exercises of this lesson, every field is controlled.
⚠️ Fields you can't type in, and forms that reload the page
valuewithoutonChange. The field can't be typed in. Add both.- Forgetting
e.preventDefault(). The page reloads as soon as the form is sent, so the state and theconsole.logoutput are lost. The first line ofhandleSubmitis almost alwayse.preventDefault(). - An
undefinedstarting value.useState()and thenvalue={name}makes the field start out uncontrolled, because avaluethat isundefinedcounts as no value. React warns whennamechanges to a string. Start fromuseState(""). - Checkboxes and numbers. A checkbox is read with
checked={agreed}ande.target.checked, notvalue. Hereagreedis a state that holds true or false. From an input withtype="number",e.target.valueis still a string:"5" + 1gives"51". Convert it first withNumber(e.target.value).
TL;DR: A controlled component is an input whose contents are controlled by state. value={email} carries the contents from state to the screen, and onChange={(e) => setEmail(e.target.value)} carries every keystroke to state. Its starting value is useState(""). A form is handled with onSubmit on the <form>, with a type="submit" button inside the form. The handler handleSubmit starts with e.preventDefault() so the page doesn't reload. The state can be used right away, for example console.log(username) or a preview <p>{email}</p>. Checkboxes use checked, and numbers from an input are still strings.
⚡ A controlled input: both directions
Write:
<input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<p id="preview">{email}</p>
Meaning: email is a state, and setEmail is its setter. An input whose contents are controlled by state like this is called a controlled component. value={email} is the direction from state to screen, and onChange is the direction from typing to state. The field and the preview always match. The starting value is useState(""), because the field starts empty.
⚡ value without onChange
Guess first: a field has value={email} but no onChange. You type rin. What's in the field?
Nothing. What you type never reaches state, so value stays "", and on every render React writes the field back to empty.
Meaning: Add both: value and onChange.
⚡ Forms: onSubmit and preventDefault
Write:
const handleSubmit = (e) => {
e.preventDefault() // stop the browser from reloading the page
console.log(username) // prints what's in the field right now, e.g. Budi
}
return (
<form onSubmit={handleSubmit}>
<input id="username" value={username} onChange={(e) => setUsername(e.target.value)} />
<button id="submit" type="submit">Login</button>
</form>
)
Meaning: username is a state that holds what's in the field. onSubmit goes on the <form>, so both a click on the type="submit" button and Enter trigger it. e.preventDefault() cancels the browser's built-in action (reloading the page), so the state and the console output aren't lost.