1. Forms in React
A form in React is a way to gather input from the user, like text fields, checkboxes, radio buttons, etc.
In React, handling forms is a little different than plain HTML because React controls the state of the input elements.
2. Controlled Component
A controlled component is an input element whose value is controlled by React state. In other words:
- React state is the “single source of truth.”
- The value of the input comes from state.
- Any change in input updates the state via
onChange
.
This allows React to fully control what’s displayed in the input.
Example of Controlled Component
import React, { useState } from "react";
function ControlledForm() {
// Step 1: Create state for input
const [name, setName] = useState("");
// Step 2: Handle input change
const handleChange = (e) => {
setName(e.target.value);
};
// Step 3: Handle form submit
const handleSubmit = (e) => {
e.preventDefault(); // prevent page reload
alert(`Hello, ${name}!`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;
Explanation:
value={name}
→ The input value comes from the React state.onChange={handleChange}
→ Updates the state whenever the user types something.handleSubmit
→ Can use the state value to process the form data.
✅ This ensures React has full control over the form input.
Why use controlled components?
- Makes form data easily accessible in React.
- Allows validation, formatting, or conditionally enabling/disabling inputs.
- Keeps UI and data in sync.