After completing this material, you will be able to:
onChange events for multiple form inputs.Forms are essential for collecting user input in a React application. Unlike traditional HTML forms, React uses controlled components to manage form state.
A simple form component in React looks like this:
function MyForm() {
const [inputValue, setInputValue] = useState("");
return (
);
}
Instead of writing separate handlers for each input, you can use a single event handler:
function MyForm() {
const [formData, setFormData] = useState({ name: "", email: "" });
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
return (
);
}
A controlled input is an input element whose value is controlled by React state.
You can implement validation inside the event handler:
function MyForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const handleChange = (e) => {
const value = e.target.value;
setEmail(value);
setError(value.includes("@") ? "" : "Invalid email format");
};
return (
);
}
Use the onSubmit event to handle form submissions:
function MyForm() {
const [formData, setFormData] = useState({ name: "", email: "" });
const handleSubmit = (e) => {
e.preventDefault();
console.log("Form submitted:", formData);
};
return (
);
}
In this reading, you learned:
To continue learning, visit:
Understanding forms in React is crucial for handling user input effectively. Controlled components ensure state synchronization, and event handlers allow for efficient input management.