What are controlled components?
In React, controlled components are form elements whose values are entirely managed by React state. Instead of the DOM managing its own state (like a traditional HTML input), a controlled component's value is driven by a piece of state within your React component. This gives React full control over the form data.
Definition
A controlled component is an input form element (like <input>, <textarea>, or <select>) whose value is controlled by the React state. When the user types into a controlled input, the component's state is updated via an event handler, and the input's value is then re-rendered with the new state value. This creates a single source of truth for the input data, residing in the React component's state, rather than the DOM.
How They Work
- The form element's value is set to a piece of state (e.g.,
value={this.state.inputValue}in a class component orvalue={inputValue}in a functional component). - An
onChangeevent handler is attached to the form element. - When the input value changes (e.g., user types), the
onChangehandler is triggered. - Inside the
onChangehandler,setState(or the state setter function fromuseState) is called to update the component's state with the new input value. - The component re-renders, and the input element's value is updated to reflect the new state.
Example
Here's a simple example of a controlled input field in a functional React component:
import React, { useState } from 'react';
function ControlledInput() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
return (
<div>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<p>Hello, {name}!</p>
</div>
);
}
export default ControlledInput;
Benefits
- Instant Validation: You can implement validation logic directly in the
onChangehandler or derive it from the state, providing immediate feedback to the user. - Conditional Disabling/Enabling: Easily control form element properties (like
disabled) based on other state or input values. - Form Manipulation: Transform, format, or filter user input in real-time before it's displayed.
- Single Source of Truth: The component's state is the definitive source for the form data, simplifying data flow and debugging.
- Easier Integration: Simpler to integrate with other UI libraries or create custom input components.
When to Use
Controlled components are generally the preferred way to handle form inputs in React for most scenarios where you need to read, validate, or manipulate the input value. They provide a predictable data flow and make it easier to manage the state of your application. While uncontrolled components exist for simpler cases or integrating with non-React code, controlled components offer superior control and maintainability for robust applications.