Controlled components in React are input elements whose values are controlled by the component’s state. This means that any changes to the input fields will be reflected in the state, and vice versa. Using controlled components makes it easier to handle and manage form data, validation, and other input-related logic.
Steps to Create Controlled Components
- Initialize State: Use the
useState
hook to initialize state for form inputs. - Create Input Elements: Bind the input elements to the state.
- Handle Changes: Update the state on input changes.
Example: A Simple Form with Controlled Components
Let’s create a simple form with two controlled input fields: a text input for the name and an email input.
import React, { useState } from 'react';
const ControlledForm = () => {
// Step 1: Initialize state
const [formData, setFormData] = useState({
name: '',
email: '',
});
// Step 3: Handle changes
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission
console.log('Form data submitted:', formData);
};
return (
);
};
export default ControlledForm;
Handling Multiple Input Types
You can handle various input types like checkboxes, radio buttons, and selects using the same approach. Here’s an example with more input types:
import React, { useState } from 'react';
const ControlledForm = () => {
// Step 1: Initialize state
const [formData, setFormData] = useState({
name: '',
email: '',
agreeToTerms: false,
gender: '',
});
// Step 3: Handle changes
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setFormData({
...formData,
[name]: type === 'checkbox' ? checked : value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission
console.log('Form data submitted:', formData);
};
return (
);
};
export default ControlledForm;
Benefits of Controlled Components
- Single Source of Truth: The state of your application is the single source of truth for all input values.
- Validation: You can easily validate inputs and provide immediate feedback to the user.
- Flexibility: It’s easier to integrate with other state-based logic and manage complex forms.