Controlled Component
What is a Controlled Component?
A controlled component is a form input field whose value is controlled by React using state.
That means:
- The value typed in the input is stored in a
useState()
variable. - Whenever the user types something, the state is updated.
- The input field shows the value from the state.
Benefits
- Single Source of Truth
- Validation and Manipulation Before Submit
- Dynamic Updates Values
How to idenitfy this is a Controlled component
- Error if we dont use Controlled value properly .
- Make Form get Input field values.
- Display input field values.
Example
import { useState } from "react";
function App() {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const [email, setEmail] = useState("");
return (
<div>
<h1>Controlled Component</h1>
<form action="" method="get">
<input
type="text"
onChange={(event) => setName(event.target.value)}
placeholder="Enter Name"
value={name}
/>
<br />
<br />
<input
type="password"
onChange={(event) => setPassword(event.target.value)}
placeholder="Enter Password"
value={password}
/>
<br />
<br />
<input
type="text"
onChange={(event) => setEmail(event.target.value)}
placeholder="Enter Email"
value={email}
/>
<br />
<br />
<button>Submit</button>
<button
onClick={() => {
setName("");
setEmail("");
setPassword("");
}}
>
Clear
</button>
<h1>{name}</h1>
<h1>{password}</h1>
<h1>{email}</h1>
</form>
</div>
);
}
Code Explanation (Simple)
useState("")
: Creates state with empty valueonChange={(e) => setName(e.target.value)}
: Every time user types, the value updates in statevalue={name}
: Binds input field to state, so it's a controlled component- Clear button: Resets all values to empty