Lesson 19 of 3063%
(Progress persistence is disabled until Phase 9)
React
Beginner
Controlled Components
Synchronizing input fields with React state.
In HTML, form elements like <input> naturally keep their own internal state.
In React, it’s a best practice to make the React state the “Single Source of Truth”. We do this by tying the input’s value to a state variable, and updating that state on onChange.
This is called a Controlled Component.
function TextInput() {
const [text, setText] = React.useState("");
return (
<div>
<input
value={text}
onChange={(e) => setText(e.target.value)}
/>
<p>You typed: {text}</p>
</div>
);
}
Now React has complete control over what is displayed in the input box!
Try It Yourself