logo
Back to blogs

Controlled and Uncontrolled Components

Mar 10, 2025 - 5 min read

Controlled and Uncontrolled Components

Example for Uncontrolled Components:

uncontrolled-component.tsx
1import React from "react"; 2 3export default function UncontrolledComponent() { 4 const inputRef = React.useRef < HTMLInputElement > null; 5 6 const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { 7 e.preventDefault(); 8 alert(inputRef.current?.value); 9 }; 10 11 return ( 12 <form onSubmit={handleSubmit}> 13 <input type="text" ref={inputRef} /> 14 <button type="submit">Submit</button> 15 </form> 16 ); 17}

In this example, we have a simple form with an input field and a submit button. The input field is an uncontrolled component because we are using the ref attribute to access the input field's value directly. When the form is submitted, we use the inputRef.current.value to get the input field's value and show an alert with the value.

Example for Controlled Components:

controlled-component.tsx
1import React, { useState } from "react"; 2 3export default function ControlledComponent() { 4 const [value, setValue] = useState(""); 5 6 const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { 7 setValue(e.target.value); 8 }; 9 10 const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { 11 e.preventDefault(); 12 alert(value); 13 }; 14 15 return ( 16 <form onSubmit={handleSubmit}> 17 <input type="text" value={value} onChange={handleChange} /> 18 <button type="submit">Submit</button> 19 </form> 20 ); 21}

In this example, we have a simple form with an input field and a submit button. The input field is a controlled component because we are using the value attribute to set the input field's value and the onChange attribute to update the input field's value. When the form is submitted, we use the value state to get the input field's value and show an alert with the value.