DEV Community

Aman Kureshi
Aman Kureshi

Posted on

šŸ“ Form Handling in React — Controlling User Input the Right Way

šŸŽÆ Why controlled components?
• You can track input values in real-time
• Easy validation and manipulation
• Full control over user interaction

šŸ‘Øā€šŸ’» Example:

function MyForm() {
const [name, setName] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
alert(
Submitted: ${name});
};
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)