React ยท Chapter 10 of 42
Forms
Forms in React work similarly to HTML forms, but React gives you more control over form data using state. You typically handle the `onSubmit` event and prevent the default page reload.
React forms can be controlled (state drives the input value) or uncontrolled (the DOM manages its own state).
Handling submit
Use `onSubmit={handleSubmit}` on the `<form>` element, and call `event.preventDefault()` to stop the browser's default full-page reload.
Collecting data
Combine controlled inputs with state to gather and validate form values before submission.
Example 1 (jsx)
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log("Form submitted!");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}Output
Form submitted!preventDefault() stops the browser from reloading the page.
Key points
- Use onSubmit to handle form submission in React.
- Call event.preventDefault() to avoid a full page reload.
- Forms can be controlled (state-driven) or uncontrolled (ref-driven).
- Validate and process form data in the submit handler.
๐ก Note: Controlled forms are recommended for most use cases since they keep the UI and data in sync.
