Skip to main content

Understanding Controlled Components in React

In React, a component that controls the input elements within the forms on subsequent user input is known as a Controlled Component.

How Does It Work?

In a controlled component, the value of the input element is always driven by the state of the component.

Here’s a simple example of a controlled component:

import React, { useState } from 'react';

function MyForm() {
const [name, setName] = useState('');

const handleChange = (event) => {
setName(event.target.value);
};

return (
<form>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}

export default MyForm;

In this example, the MyForm component has a state variable name, which is updated every time the user types into the input field. The handleChange function is called on every keystroke to update the React state.

Why Use Controlled Components?

Controlled components offer several benefits:

  • Consistent Data: Since the React state is the single source of truth, the data in your UI is always consistent with your state.
  • Instant Input Validation: You can validate or transform user input instantly as they type.
  • Conditionally Disable Submit Button: You can disable the submit button until the user fills out all the required fields.