Flat Preloader Icon

Controlled Components

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 (
    <form onSubmit={handleSubmit}>
      {/* Step 2: Create input elements */}
      <div>
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
        />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

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 (
    <form onSubmit={handleSubmit}>
      {/* Step 2: Create input elements */}
      <div>
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
        />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
        />
      </div>
      <div>
        <label>
          <input
            type="checkbox"
            name="agreeToTerms"
            checked={formData.agreeToTerms}
            onChange={handleChange}
          />
          Agree to terms
        </label>
      </div>
      <div>
        <label>Gender:</label>
        <label>
          <input
            type="radio"
            name="gender"
            value="male"
            checked={formData.gender === 'male'}
            onChange={handleChange}
          />
          Male
        </label>
        <label>
          <input
            type="radio"
            name="gender"
            value="female"
            checked={formData.gender === 'female'}
            onChange={handleChange}
          />
          Female
        </label>
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default ControlledForm;

				
			

Benefits of Controlled Components

  1. Single Source of Truth: The state of your application is the single source of truth for all input values.
  2. Validation: You can easily validate inputs and provide immediate feedback to the user.
  3. Flexibility: It’s easier to integrate with other state-based logic and manage complex forms.