The Tech Platform

Oct 26, 20212 min

The Difference Between Controlled and Uncontrolled Components in React

Controlled Component

Controlled components in React are those in which form data is handled by the component’s state.

Forms are used to store information in a document section. The information from this form is typically sent to a server to perform an action. This data is held by form input elements and control elements, such as input, select, textarea, etc., which maintain and control their states or values.

Example:

function App() {
 
const [name, setName] = useState("");
 
const [email, setEmail] = useState("");
 

 
function onSubmit() {
 
console.log("Name value: " + name);
 
console.log("Email value: " + email);
 
}
 
return (
 
<form onSubmit={onSubmit}>
 
<input
 
type="text"
 
name="name"
 
value={name}
 
onChange={(e) => setName(e.target.value)}
 
required
 
/>
 
<input
 
type="email"
 
name="email"
 
value={email}
 
onChange={(e) => setEmail(e.target.value)}
 
required
 
/>
 
<input type="submit" value="Submit" />
 
</form>
 
);
 
}

Source: LogRocket

Here we have two states: name and email. These states are assigned to the value property of the name and email input elements.

Uncontrolled Component

t is similar to the traditional HTML form inputs. Here, the form data is handled by the DOM itself. It maintains their own state and will be updated when the input value changes. To write an uncontrolled component, there is no need to write an event handler for every state update, and you can use a ref to access the value of the form from the DOM.

Example:

function App() {
 
function onSubmit() {
 
console.log("Name value: " + window.name.value);
 
console.log("Email value: " + window.email.value);
 
}
 
return (
 
<form onSubmit={onSubmit}>
 
<input type="text" name="name" id="name" required />
 
<input type="email" name="email" id="email" required />
 
<input type="submit" value="Submit" />
 
</form>
 
);
 
}

Source: LogRocket

In the above code, we assigned ID attributes to the name and email input elements with values name and email, respectively. We used these id attributes to get the value of the input element when the form is being submitted.

The above component is an uncontrolled component because React has no control over the values of the form input elements.

Difference Between Controlled and Uncontrolled Component

Controlled Uncontrolled

The Tech Platform

www.thetechplatform.com

    0