Basic Forms Handling
Subject: React
π What Is It?
Form handling in React means managing user input (e.g., from <input>, <textarea>, <select>, etc.) using React state. In React, we use controlled components, meaning the form elements' values are controlled by React's useState.
π§ Why Controlled Components?
- Keeps form values in React memory, not the DOM
- Makes it easy to validate, submit, and reset forms
- Keeps UI and data in sync
β 1. Single Input Field Example
π§ Logic Breakdown:
| Step | What Happens |
|---|---|
useState("") | Stores input value in React state |
value={name} | Binds input value to state (controlled) |
onChange={} | Updates state as the user types |
onSubmit={} | Handles what happens when form submits |
β 2. Multiple Fields Example
π Key Concepts:
| Concept | Description |
|---|---|
name attribute | Determines which field in state to update |
setFormData({...}) | Keeps all form data in one object |
[name]: value | Dynamic key to update correct field |
onChange shared | One handler updates all fields |
β 3. Select, Checkbox, Textarea Inputs
β οΈ Form Handling Best Practices
| β Do | β Don't |
|---|---|
Use useState to control values | Don't let browser handle form state |
Use e.preventDefault() | Avoid page reload |
Use shared onChange | Donβt write a handler per input |
| Validate before submit | Donβt blindly trust user input |
β Summary Table
| Task | React Way |
|---|---|
| Read input | value={state} |
| Update input | onChange={e => setState(e.target.value)} |
| Submit form | onSubmit={handleSubmit} |
| Handle multiple | Object state + [name]: value pattern |
| Prevent page refresh | e.preventDefault() |
Advertisement Slot 1
Advertisement Slot 2