šÆ 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)