π― Why controlled components?
β’ You can track input values in real-time
β’ Easy validation and manipulation
β’ Full control over user interaction
π¨βπ» Example:
function MyForm() {
Submitted: ${name}
const [name, setName] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
alert();
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<button type="submit">Submit</button>
</form>
);
}
π Key points:
β’ Use useState() for each input field
β’ Use onChange to update the state
β’ Prevent default form submission with e.preventDefault()
React forms give you power and flexibility β especially for validations and dynamic forms.
Top comments (0)