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:

  1. The value typed in the input is stored in a useState() variable.
  2. Whenever the user types something, the state is updated.
  3. The input field shows the value from the state.


Benefits

  1. Single Source of Truth
  2. Validation and Manipulation Before Submit
  3. Dynamic Updates Values


How to idenitfy this is a Controlled component

  1. Error if we dont use Controlled value properly .
  2. Make Form get Input field values.
  3. 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)

  1. useState(""): Creates state with empty value
  2. onChange={(e) => setName(e.target.value)}: Every time user types, the value updates in state
  3. value={name}: Binds input field to state, so it's a controlled component
  4. Clear button: Resets all values to empty