A controlled component is a fundamental concept in React that refers to an input element whose value is controlled by the state of the component. This means that the React component maintains the current value of the input field, and any changes to the input are handled through event handlers. Controlled components provide a way to manage form data and ensure that the UI is always in sync with the underlying state.
In contrast to uncontrolled components, where the DOM itself manages the input state, controlled components offer better control and validation over user inputs. This approach is particularly useful in complex forms where you need to enforce certain constraints or perform actions based on user input.
In a controlled component, the value of the input is set via the component's state, and changes are handled through an event handler. Here’s a simple example:
import React, { useState } from 'react';
function ControlledInput() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<div>
<input type="text" value={value} onChange={handleChange} />
<p>Current Value: {value}</p>
</div>
);
}
In summary, controlled components are a powerful feature of React that enable developers to manage form inputs effectively. By understanding how to implement them correctly and adhering to best practices, you can create robust and user-friendly forms in your applications.