React Tutorial
Forms and Controlled Inputs
Connect form controls to state, validate input and handle submission deliberately.
Concept
A controlled input receives its current value from state and updates that state in an onChange handler. This makes the displayed value and application data follow one source of truth.
Form submission should be handled at the form level. Prevent the browser default only when the application will process the data itself, then validate required values and provide clear feedback.
Example
import { useState } from "react";
export default function SkillForm() {
const [skill, setSkill] = useState("");
return <form onSubmit={event => event.preventDefault()}>
<input value={skill} onChange={event => setSkill(event.target.value)} />
<button type="submit">Save</button>
</form>;
}
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.
Practice Tasks
- Create a controlled name input.
- Disable submit while the trimmed input is empty.
- Display a submitted value without clearing it unexpectedly.
Key Takeaways
- Controlled inputs read from state.
- onChange keeps state synchronized.
- Submission and validation belong to explicit handlers.