Popular Searches
Popular Course Categories
Popular Courses

Controlled Components

Controlled Components

React Forms

Controlled Components in React JS

Controlled Components are an important concept in React JS used to manage form elements through React state. In a controlled component, the value of an input field, textarea, dropdown, checkbox, or radio button is controlled by a state variable. When the user changes the input, an event handler updates the state, and React renders the latest value. Controlled components are useful for form validation, live search, registration forms, login pages, dynamic inputs, and interactive user interfaces.

Learn more: JustAcademy React JS Training | Register for React JS Course Demo


1. What Are Controlled Components?

A Controlled Component is a form element whose current value is managed by React state rather than being managed independently by the DOM. React provides the value through a prop, and an event handler updates the state when the user interacts with the field.

For example, if a text input uses value={name}, its displayed value comes from the React state variable name. When the user types, the onChange handler updates that variable.

Basic Example

import { useState } from "react";

function NameInput() {
  const [name, setName] = useState("");

  return (
    <div>
      <label htmlFor="name">Enter Your Name:</label>
      <input
        id="name"
        type="text"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <p>Your Name: {name}</p>
    </div>
  );
}

export default NameInput;

Explanation:

  • useState("") initializes the name as an empty string.
  • value={name} connects the input to React state.
  • onChange runs when the user changes the input.
  • event.target.value reads the current text from the input.
  • setName() updates the state.
  • The paragraph displays the current name immediately after the state update.

2. How Do Controlled Components Work?

Controlled components follow a simple data flow between React state and the form element.

  1. Initial state: React initializes the state with a default value.
  2. Rendering: React passes the state value to the form element through its value or checked prop.
  3. User interaction: The user types, selects an option, or clicks a checkbox.
  4. Event handling: The onChange handler reads the new value or checked status.
  5. State update: The handler updates the relevant state variable.
  6. Re-rendering: React renders the form element with the updated state.

This process keeps the displayed form value synchronized with the React state.

3. Controlled Components Using useState()

The useState() Hook is commonly used to manage controlled form elements in functional components. It provides the current state and a setter function to update it.

import { useState } from "react";

function AgeInput() {
  const [age, setAge] = useState("");

  return (
    <div>
      <label htmlFor="age">Enter Your Age:</label>
      <input
        id="age"
        type="number"
        value={age}
        onChange={(event) => setAge(event.target.value)}
      />
      <p>Age entered: {age}</p>
    </div>
  );
}

export default AgeInput;

Important: The value from a number input is still provided as a string through event.target.value. Convert it to a number when numerical calculations are needed, and handle an empty string separately if necessary.

4. Controlled Text Inputs

Text inputs are among the most common controlled components. They are useful for collecting names, usernames, email addresses, addresses, and other text values.

import { useState } from "react";

function UsernameForm() {
  const [username, setUsername] = useState("");

  return (
    <div>
      <input
        type="text"
        value={username}
        onChange={(event) => setUsername(event.target.value)}
        placeholder="Enter username"
      />
      <p>Username: {username}</p>
    </div>
  );
}

export default UsernameForm;

Whenever the user types, the state changes and React updates the input value and paragraph.

5. Controlled Textarea

A textarea allows users to enter multiline text, such as comments, descriptions, or feedback. A controlled textarea uses value and onChange in the same way as a text input.

import { useState } from "react";

function FeedbackForm() {
  const [feedback, setFeedback] = useState("");

  return (
    <div>
      <label htmlFor="feedback">Your Feedback:</label>
      <textarea
        id="feedback"
        value={feedback}
        onChange={(event) => setFeedback(event.target.value)}
        placeholder="Write your feedback"
        rows={4}
      />
      <p>Feedback length: {feedback.length} characters</p>
    </div>
  );
}

export default FeedbackForm;

Explanation: The feedback state stores the textarea's current content. The character count updates automatically as the user types.

6. Controlled Select Dropdown

A controlled dropdown allows React to manage the currently selected option. The value prop belongs on the select element, and the onChange handler updates its state.

import { useState } from "react";

function CourseSelector() {
  const [course, setCourse] = useState("");

  return (
    <div>
      <label htmlFor="course">Choose a Course:</label>
      <select
        id="course"
        value={course}
        onChange={(event) => setCourse(event.target.value)}
      >
        <option value="">Select a course</option>
        <option value="react">React JS</option>
        <option value="flutter">Flutter</option>
        <option value="selenium">Selenium</option>
      </select>
      <p>Selected course: {course || "None"}</p>
    </div>
  );
}

export default CourseSelector;

Explanation: The selected course is stored in the course state. When a user selects a different option, React updates the state and the selected value displayed on the page.

7. Controlled Checkboxes

Checkboxes are used when users need to select or deselect an option. A controlled checkbox uses the Boolean checked prop and reads its new status from event.target.checked.

import { useState } from "react";

function TermsCheckbox() {
  const [accepted, setAccepted] = useState(false);

  return (
    <div>
      <label>
        <input
          type="checkbox"
          checked={accepted}
          onChange={(event) => setAccepted(event.target.checked)}
        />
        I accept the terms and conditions.
      </label>
      <p>Accepted: {accepted ? "Yes" : "No"}</p>
    </div>
  );
}

export default TermsCheckbox;

Important: Use checked rather than value to control whether a checkbox is selected. The checkbox's submitted value and its checked status are two different concepts.

8. Controlled Radio Buttons

Radio buttons allow users to select one option from a group. React can control the group by storing the selected option in a state variable.

import { useState } from "react";

function GenderSelector() {
  const [gender, setGender] = useState("");

  return (
    <div>
      <p>Select an Option:</p>

      <label>
        <input
          type="radio"
          name="gender"
          value="male"
          checked={gender === "male"}
          onChange={(event) => setGender(event.target.value)}
        />
        Male
      </label>

      <label>
        <input
          type="radio"
          name="gender"
          value="female"
          checked={gender === "female"}
          onChange={(event) => setGender(event.target.value)}
        />
        Female
      </label>

      <label>
        <input
          type="radio"
          name="gender"
          value="other"
          checked={gender === "other"}
          onChange={(event) => setGender(event.target.value)}
        />
        Other
      </label>

      <p>Selected option: {gender || "None"}</p>
    </div>
  );
}

export default GenderSelector;

Explanation: The selected radio button is determined by comparing its value with the gender state. All radio buttons in the group share the same name.

9. Managing Multiple Controlled Inputs

A form may contain several fields, such as name, email, phone number, and city. Instead of creating a separate state variable and handler for every field, you can store related values in one state object.

import { useState } from "react";

function RegistrationForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    city: ""
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setFormData((previousData) => ({
      ...previousData,
      [name]: value
    }));
  }

  return (
    <form>
      <input
        name="name"
        value={formData.name}
        onChange={handleChange}
        placeholder="Enter name"
      />

      <input
        name="email"
        type="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Enter email"
      />

      <input
        name="phone"
        type="tel"
        value={formData.phone}
        onChange={handleChange}
        placeholder="Enter phone"
      />

      <input
        name="city"
        value={formData.city}
        onChange={handleChange}
        placeholder="Enter city"
      />

      <pre>{JSON.stringify(formData, null, 2)}</pre>
    </form>
  );
}

export default RegistrationForm;

How it works:

  • The state object stores all four form values.
  • Every input uses a name matching its state property.
  • The shared handleChange() function reads the field name and new value.
  • The spread operator preserves all existing fields.
  • The computed property [name] updates only the field that changed.

10. Handling Different Input Types with One Handler

A shared change handler can manage text inputs, number inputs, checkboxes, and other common form controls. For checkboxes, read checked; for most other input types, read value.

function handleChange(event) {
  const { name, value, type, checked } = event.target;

  setFormData((previousData) => ({
    ...previousData,
    [name]: type === "checkbox" ? checked : value
  }));
}

This approach reduces repeated code. For multiple-select elements or specialized inputs, additional handling may be necessary because their values may have a different shape.

11. Form Validation with Controlled Components

Controlled components make it convenient to validate values as the user types or when a form is submitted. You can store error messages in state and display them near the corresponding field.

import { useState } from "react";

function EmailValidationForm() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  function handleSubmit(event) {
    event.preventDefault();

    const trimmedEmail = email.trim();

    if (!trimmedEmail) {
      setError("Email is required.");
      return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedEmail)) {
      setError("Please enter a valid email address.");
      return;
    }

    setError("");
    alert("Email validation successful.");
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label htmlFor="email">Email Address:</label>
      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => {
          setEmail(event.target.value);
          setError("");
        }}
        aria-invalid={Boolean(error)}
        aria-describedby={error ? "email-error" : undefined}
      />

      {error && (
        <p id="email-error" role="alert">{error}</p>
      )}

      <button type="submit">Submit</button>
    </form>
  );
}

export default EmailValidationForm;

Explanation:

  1. The email state stores the user's input.
  2. The form submission handler prevents the default page reload.
  3. The handler checks whether the email is empty and performs a basic format check.
  4. If validation fails, the error message appears.
  5. If validation succeeds, the error is cleared and a confirmation appears.

Note: This regular expression provides only a basic format check. Frontend validation improves user experience but should not replace server-side validation.

12. Updating State from User Actions

Controlled inputs can also be updated by buttons or other UI controls. Since the value comes from React state, updating that state changes the displayed value.

import { useState } from "react";

function ControlledInputActions() {
  const [name, setName] = useState("");

  return (
    <div>
      <input
        value={name}
        onChange={(event) => setName(event.target.value)}
        placeholder="Enter name"
      />

      <button type="button" onClick={() => setName("Manish")}>
        Set Example Name
      </button>

      <button type="button" onClick={() => setName("")}>
        Clear
      </button>

      <p>Current value: {name || "Empty"}</p>
    </div>
  );
}

export default ControlledInputActions;

This example demonstrates that controlled inputs can be updated through typing, button clicks, or other state-changing actions.

13. Controlled Components vs. Uncontrolled Components

Controlled and uncontrolled components differ in where the current form value is managed.

Feature Controlled Component Uncontrolled Component
Value management React state DOM element
Text input prop value defaultValue
Checkbox prop checked defaultChecked
Change handling Usually uses onChange and a state setter Can be read when needed using FormData or a ref
Live validation Convenient because values are available in state Possible, but requires reading the DOM or using events
Programmatic updates Update the state variable Often use a ref or native DOM behavior
Typical use Interactive forms, dynamic validation, live previews Simple forms where values are primarily needed at submission

14. Common Mistakes in Controlled Components

Mistake Problem Solution
Using value without onChange The input behaves as read-only. Add an onChange handler that updates state, or intentionally use readOnly.
Initializing a text input with undefined or null The input may switch between uncontrolled and controlled modes. Initialize the value with an empty string or another string.
Using value to control a checkbox The selected status is not managed correctly. Use the Boolean checked prop.
Reading event.target.value for checkbox status It does not represent whether the checkbox is selected. Use event.target.checked.
Updating the input state asynchronously during typing The input may feel unresponsive or its caret may jump. Update the controlled value synchronously in onChange.
Replacing the entire state object accidentally Other input values may be lost. Preserve existing properties with the spread operator.
Missing the name attribute in a shared handler The handler may not know which field to update. Give each field the appropriate name.
Using only client-side validation Invalid data can still reach a backend through other means. Validate data on the server as well.

15. Best Practices for Controlled Components

  • Initialize text inputs with strings and checkbox values with Booleans.
  • Keep the input's state update synchronous inside onChange.
  • Use value for controlled text inputs and selects.
  • Use checked for controlled checkboxes and radio buttons.
  • Use a shared change handler for related fields when it improves code clarity.
  • Use the spread operator when updating an object containing several form values.
  • Provide labels and accessible validation messages.
  • Validate form values before processing them and validate untrusted data on the server.
  • Keep form state in the smallest component that needs to read or update it.
  • Avoid unnecessary re-renders of large parts of the application when input state changes frequently.

16. Mini Project: Student Registration Form

Objective: Build a controlled student registration form that collects a name, email address, course, and terms acceptance. The project demonstrates state management, multiple input types, validation, and form submission.

Complete Code

import { useState } from "react";

function StudentRegistrationForm() {
  const initialFormData = {
    name: "",
    email: "",
    course: "",
    acceptedTerms: false
  };

  const [formData, setFormData] = useState(initialFormData);
  const [message, setMessage] = useState("");

  function handleChange(event) {
    const { name, value, type, checked } = event.target;

    setFormData((previousData) => ({
      ...previousData,
      [name]: type === "checkbox" ? checked : value
    }));

    setMessage("");
  }

  function handleSubmit(event) {
    event.preventDefault();

    if (!formData.acceptedTerms) {
      setMessage("Please accept the terms and conditions.");
      return;
    }

    setMessage(
      `Form validated for ${formData.name}. Course: ${formData.course}.`
    );
  }

  function resetForm() {
    setFormData(initialFormData);
    setMessage("");
  }

  return (
    <div>
      <h1>Student Registration</h1>

      <form onSubmit={handleSubmit}>
        <label htmlFor="name">Full Name:</label>
        <input
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
          required
        />

        <label htmlFor="email">Email Address:</label>
        <input
          id="email"
          name="email"
          type="email"
          value={formData.email}
          onChange={handleChange}
          required
        />

        <label htmlFor="course">Select Course:</label>
        <select
          id="course"
          name="course"
          value={formData.course}
          onChange={handleChange}
          required
        >
          <option value="">Choose a course</option>
          <option value="react">React JS</option>
          <option value="flutter">Flutter</option>
          <option value="selenium">Selenium</option>
        </select>

        <label>
          <input
            type="checkbox"
            name="acceptedTerms"
            checked={formData.acceptedTerms}
            onChange={handleChange}
          />
          I accept the terms and conditions.
        </label>

        <button type="submit">Register</button>
        <button type="button" onClick={resetForm}>Reset</button>
      </form>

      {message && <p role="status">{message}</p>}
    </div>
  );
}

export default StudentRegistrationForm;

How the Project Works

  1. The state object stores the name, email, course, and checkbox status.
  2. Each input receives its current value from React state.
  3. The shared handler updates the relevant property whenever an input changes.
  4. The browser checks required fields and the email input's basic format.
  5. The submit handler checks the terms acceptance and displays a message.
  6. The Reset button restores the initial state.

Note: This example performs client-side validation only. A production registration system must submit data to a backend and validate it securely on the server.

17. Interview Questions and Answers

Q1. What is a controlled component in React?

Answer: A controlled component is a form element whose current value or checked status is managed by React state and synchronized through props and event handlers.

Q2. Which Hook is commonly used for controlled components?

Answer: The useState() Hook is commonly used to store and update controlled input values in functional components.

Q3. What is the purpose of the value prop?

Answer: The value prop specifies the current value of a controlled text input, textarea, or select element.

Q4. What is the purpose of the checked prop?

Answer: The checked prop controls whether a checkbox or radio button is selected.

Q5. Why is onChange important?

Answer: The onChange handler reads the new user input and updates the state that controls the form element.

Q6. What happens if a controlled input has value but no onChange?

Answer: The input will generally behave as read-only because React keeps forcing its value to match the supplied state or prop.

Q7. What is the difference between value and defaultValue?

Answer: value controls the current value through React. defaultValue provides the initial value for an uncontrolled input.

Q8. How do you manage multiple controlled inputs?

Answer: Store related field values in an object, give each input a matching name, and use a shared handler with computed property names to update the correct field.

Q9. How do you manage a checkbox in a controlled component?

Answer: Store its Boolean status in state, pass it to checked, and update it using event.target.checked.

Q10. What are the benefits of controlled components?

Answer: They make it easier to validate input, display live feedback, coordinate form fields, reset values, and update the interface in response to user input.

18. Practice Exercises

  1. Create a controlled input that displays a user's name as they type.
  2. Build a controlled login form with email and password fields.
  3. Create a feedback form with a controlled textarea.
  4. Build a dropdown that stores a selected course in state.
  5. Create a checkbox that enables a Submit button only when selected.
  6. Build radio buttons that let users select a preferred contact method.
  7. Create a registration form that stores multiple values in one state object.
  8. Display field-specific validation errors using controlled state.
  9. Build a reset button that clears every controlled input.
  10. Create a live search input that filters a list as the user types.

19. Quick Revision

  • A controlled component gets its current form value from React state.
  • Use useState() to manage values in functional components.
  • Use value for controlled text inputs, textareas, and selects.
  • Use checked for controlled checkboxes and radio buttons.
  • Use onChange to update the backing state synchronously.
  • Use event.target.value for text values and event.target.checked for checkbox status.
  • Use object spread syntax to update one property without losing other form values.
  • Keep controlled input values initialized with appropriate types.
  • Controlled components simplify live validation, dynamic feedback, and form resets.

Conclusion

Controlled Components in React JS are fundamental to managing form data and building interactive interfaces. By connecting form values to state, handling changes through event handlers, and using the correct props for each input type, developers can create forms that support validation, live previews, dynamic updates, and reliable user interactions. Practicing controlled text inputs, dropdowns, checkboxes, radio buttons, and complete registration forms builds a strong foundation for advanced React development.


Learn React JS with JustAcademy

Explore React JS training to strengthen your understanding of components, state management, form handling, controlled inputs, validation, and interactive web development.

JustAcademy React JS Training

Register for React JS Course Demo

Official React Documentation

Previous Next
whatsapp