- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Controlled Inputs
Forms and Inputs
Controlled Inputs
A controlled input has no memory of its own. React state is the value, and typing is just a request to change that state.
The loop
Two props make an input controlled: value reads from state, and onChange writes back to it. Remove either and the input misbehaves in a specific, recognisable way.
Value in, change out
jsx
function NameField() {
const [name, setName] = React.useState("")
return (
<div>
<input
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Type your name"
/>
<p>State holds: "{name}"</p>
<button onClick={() => setName("")}>Clear</button>{" "}
<button onClick={() => setName("Ada")}>Set to Ada</button>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<NameField />)