Lesson 5 of 15
Forms and Inputs (Controlled Components)
Lesson Updated: Apr 28, 2026
Requirement
Learn how to track what a user types into an <input> field using the onChange event and useState.
Assignments (Start First)
- Simple beginner UI task: Create a
NameInputcomponent. Use state to track a string. Render an<input type="text">and a paragraph below it that says "Hello, [whatever was typed]". - Slightly improved version: Add a "Clear" button next to the input that resets the state back to an empty string when clicked.
- Practical real-world component: Build a
SubscribeFormcomponent with an email input and a "Subscribe" button. Prevent the default form submission behavior usinge.preventDefault()and alert the typed email. - "The Escalation": Create a
SearchBoxcomponent that has a live character count below it (e.g., "15/50 characters"). If the length exceeds 50, change the character count text to red.
Lessons (Optional)
- Controlled Components: In React, input fields are "controlled" by state. The input's
valueis tied directly to a state variable. - Event Object (e): When an input changes, React passes an event object to the handler. You read the typed value using
e.target.value.
The Summary and Quizzes
- Concept explanation: By controlling inputs with state, React becomes the "single source of truth" for what is currently inside the form.
- Why it works in React: As the user types, the
onChangeevent fires, updating the state. React re-renders the input immediately to display the new state value. - Challenge question: Inside an
onChangehandler function(e) => { ... }, what is the exact property path you use to get the text the user just typed?