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)