Reputation: 36520
I'm trying to understand the distinction between Controlled and Uncontrolled components in ReactJS. Could someone please explain:
Upvotes: 280
Views: 191578
Reputation: 28
managing form data (all types of inputs) are basic part of dynamic web applications. This issue which how form data is handled in a react component shape two important concepts, controlled and uncontrolled components.
Briefly, Controlled components rely on React state to manage the form data, while uncontrolled components use the DOM itself to handle form data. In this article, we will explore the difference between controlled and uncontrolled components.
What are Controlled Components?
• A Controlled Component gets its value from props and reports changes via callbacks like onChange, without managing its own state. The parent component controls it by handling state updates and passing the updated value as props. This makes the component focused only on rendering and interaction, often called a "dumb component" because logic resides in the parent.
Controlled components are form elements (like input, textarea, or select) that are managed by React state. This means that the value of the form element is set and updated through React state, making React the "single source of truth" for the form data. By controlling form elements via state, you gain more control over user interactions and can easily enforce validation, format data, and respond to changes.
• A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.
The difference between them is that components that their value is set/passed and have a callback are called controlled components.
<input type="text" value="value" onChange={handleChangeCallbackFn} />
on the other hand, traditional HTML where an input element handle their own value and can be read via refs called uncontrolled components.
<value type="text" ref={inputValue} />
Controlled components are managing their own state via setState or getting it from their parent component as props.
In most cases, it is recommended using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />{" "}
</label>
<input type="submit" value="Submit" />
</form>
Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes easier to integrate React and non-React code when using uncontrolled components. It can also be slightly less code if you want to be quick and dirty. Otherwise, you should usually use controlled components.
In HTML, form elements such as
<input />,
<textarea></textarea>,
<select></select>
typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
For example, if we want to make the previous example log the name when it is submitted, we can write the form as a controlled component:
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
Here's another example of a controlled component:
import React, { useState } from "react";
const ControlledComponentExample = () => {
const [inputValue, setInputValue] = useState("");
const handleChange = (e) => {
setInputValue(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted Value: ${inputValue}`);
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
value={inputValue} // Controlled by React state
onChange={handleChange} // Updates state on input change
/>
<button type="submit">Submit</button>
</form>
);
};
export default ControlledComponentExample;
This approach ensures that the form's value is always in sync with the component's state, making it easier to validate and manipulate data programmatically.
Benefits of Using Controlled Components:
import React, { useState } from "react";
export default function PredictableForm() {
const [name, setName] = useState("");
const handleChange = (event) => {
setName(event.target.value);
};
return (
<div>
<input type="text" value={name} onChange={handleChange} />
<p>Current value: {name}</p>
</div>
);
}
In this example, the input field and the displayed text are always synchronized, providing a predictable behavior.
Controlled components make it straightforward to implement form validation. Since the form data is stored in the component state, you can easily validate it before updating the state or on form submission.
import React, { useState } from "react";
export default function ValidatedForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const handleChange = (event) => {
const value = event.target.value;
setEmail(value);
if (!value.includes("@")) {
setError("Invalid email address");
} else {
setError("");
}
};
return (
<div>
<input type="email" value={email} onChange={handleChange} />
{error && <p style={{ color: "red" }}>{error}</p>}
</div>
);
}
Controlled components provide predictable state management, easier form validation, and seamless integration with complex UI libraries.
Controlled components provide a clear and consistent way to handle form inputs in React. By using React state to manage the values of input fields, select menus, checkboxes, and radio buttons, you ensure that the UI remains in sync with the state. This approach simplifies validation, makes data handling predictable, and facilitates integration with complex UI libraries.
What are Uncontrolled Components?
Uncontrolled components in React manage their own state internally rather than relying on React state, in another words, form data is handled by the DOM itself, rather than being fully controlled by React's state. Essentially, React does not "control" or manage the value of the input field; instead, the browser handles it. This approach is useful for simple forms where you don't need to manipulate the input data through React state updates.
import React, { Component } from "react";
class UncontrolledComponent extends Component {
constructor(props) {
super(props);
// Create a ref to hold the input DOM element
this.inputRef = React.createRef();
}
handleSubmit = () => {
// Access the input value using the ref
console.log(this.inputRef.current.value);
};
render() {
return (
<div>
{/* Use ref attribute to attach the ref to the input element */}
<input type="text" ref={this.inputRef} />
<button onClick={this.handleSubmit}>Submit</button>
</div>
);
}
}
To retrieve the value of the input field, you typically use a ref to directly access the DOM element.
Pros of Uncontrolled Components:
Uncontrolled components manage their state internally using DOM refs (useRef hook in functional components or React.createRef() in class components) to access form element values directly.
The point is In functional components, the useRef hook allows us to create a mutable reference that persists across renders. We can use this ref to directly access DOM nodes, such as input fields.
import React, { useRef } from "react";
function UncontrolledComponent() {
const inputRef = useRef(null); // Create a ref to hold the input DOM element
const handleSubmit = () => {
// Access the input value using the ref
console.log(inputRef.current.value);
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
export default UncontrolledComponent;
Important considerations in choosing Controlled or Uncontrolled components: Important considerations in choosing Controlled or Uncontrolled components:
1. Complexity of forms
Controlled components are suitable for complex forms where you need precise control over the form state and its interactions with other components, while Uncontrolled components simplify implementation for basic forms with minimal interactivity or where direct DOM manipulation suffices. Uncontrolled components are ideal for simple forms.
2. Need for Form Validation
Controlled components can easily integrated with form validation libraries (for example, Formik, Yup) since form state is managed within React state, while handling form validation with uncontrolled components can be more manual and less integrated, as form data is managed directly through DOM manipulation.
3. Integration with External Libraries
Controlled components can easily integrate with external state management solutions like Redux or React's Context API for managing global application state, whereas, handling this with uncontrolled components may require additional effort.
Upvotes: -1
Reputation: 28
Controlled components rely on React state to manage the form data, while uncontrolled components use the DOM itself to handle form data. Controlled components are form elements (like input, textarea, or select) that are managed by React state. This means that the value of the form element is set and updated through React state, making React the "single source of truth" for the form data. Here's an example of a controlled component:
import React, { useState } from 'react';
export default function ControlledComponent() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert('A name was submitted: ' + value);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={value} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
In this example:
1)The value state holds the current value of the input field. 2)The handleChange function updates the state whenever the user types in the input field. 3)The handleSubmit function handles the form submission, using the current state value.
Upvotes: 0
Reputation: 1019
According to docs:
In a controlled component, form data is handled by a React component.
The alternative is uncontrolled components, where form data is handled by the DOM itself.
Upvotes: 4
Reputation: 21
A controlled component is a preferred way to do things in React.
It allows us to keep all component states in the React state, instead of relying on the DOM to retrieve the element's value through its internal state.
A controlled component is a component that derives its input values from the state.
Upvotes: 2
Reputation: 81
https://www.youtube.com/watch?v=6L2Rd116EvY You can check that page out he explains it finely.......
Without complex words, Controlled components are components rendering form elements such as <input/>
whose value is controlled by react and react alone, For example copy the code below and try to change the input field within the DOM...
export default function Component() {
return (
<div>
<input type="text" value="somevalue" />
</div>
)
}
No matter how much you try to update the value of the input above, react won't let you. Because Reacts wants to be the one in control of the updated value using states hence the title controlled...
It's value can be updated by connecting the attributes onChange
and value
to a state as shown below, Try it out.
function Component() {
const [text,setText] = React.useState("")
return (
<div>
<input type="text" onChange={(e)=>setText(e.target.value)} value={text} />
<p>{text}</p>
</div>
)
}
Now our input can be updated and its value, used either to render something or perform instant validation....
Uncontrolled components are components that render form elements such as <input/>
whose value can be handled by the Dom element and one major difference between controlled and uncontrolled is the value attribute definition. for uncontrolled, we have a defaultValue
instead or no value at all sometimes..
function Component() {
return (
<div>
<input type="email" id="message" defaultValue="[email protected]" />
</div>
)
}
The value of the input above can be changed and is controlled by the DOM without React...
Its advice to use the Controlled Components more in react as you can perform instant validation and enforce dynamic inputs.
Upvotes: 6
Reputation: 81
Controlled component: Form data are handled by a React component.
The flow of a Controlled Component in ReactJS image
Uncontrolled components: form data are handled by the DOM itself.
The flow of an Uncontrolled Component in ReactJS image
Upvotes: 8
Reputation: 195
Controlled components do not hold their state.
Data they need is passed down to them from a parent component.
They interact with this data by callback functions, which are also passed from the parent to the child.
Upvotes: 5
Reputation: 2017
Uncontrolled component and Controlled component are terms used to describe React components that render HTML form elements. Every time you create a React component that renders an HTML form element, you are creating one of those two.
Uncontrolled components and Controlled components differ in the way they access the data from the form elements (<input>
, <textarea>
, <select>
).
An uncontrolled component is a component that renders form elements, where the form element's data is handled by the DOM (default DOM behavior). To access the input's DOM node and extract its value you can use a ref.
const { useRef } from 'react';
function Example () {
const inputRef = useRef(null);
return <input type="text" defaultValue="bar" ref={inputRef} />
}
A controlled component is a component that renders form elements and controls them by keeping the form data in the component's state.
In a controlled component, the form element's data is handled by the React component (not DOM) and kept in the component's state. A controlled component basically overrides the default behavior of the HTML form elements.
We create a controlled component by connecting the form element (<input>
, <textarea>
or <select>
) to the state by setting its attribute value
and the event onChange
.
const { useState } from 'react';
function Controlled () {
const [email, setEmail] = useState();
const handleInput = (e) => setEmail(e.target.value);
return <input type="text" value={email} onChange={handleInput} />;
}
Upvotes: 98
Reputation: 67
Controlled components are mainly those where any prop value of the component is either from the parent component or from the store (as in case of redux). Example:
<ControlledComp value={this.props.fromParent}/>
In case of an uncontrolled component, the component value can be taken from the state of the component depending on the event handling. Example:
<UncontrolledComp value={this.state.independentValue}/>
Upvotes: 0
Reputation:
Controlled component is component that get the changed value from the callback function and uncontrolled component is component that have the one from the DOM. For example, When input value is changed,we can use onChange function in Controlled Component and also we can get the value using DOM like ref.
Upvotes: 9
Reputation: 52143
This relates to stateful DOM components (form elements) and the React docs explain the difference:
props
and notifies changes through callbacks like onChange
. A parent component "controls" it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a "dumb component". ref
to find its current value when you need it. This is a bit more like traditional HTML.Most native React form components support both controlled and uncontrolled usage:
// Controlled:
<input type="text" value={value} onChange={handleChange} />
// Uncontrolled:
<input type="text" defaultValue="foo" ref={inputRef} />
// Use `inputRef.current.value` to read the current value of <input>
In most (or all) cases you should use controlled components.
Upvotes: 374