Nearby lessons

21 of 44

⚛️ ReactJS – Controlled Components

📌 What are Controlled Components?

What are Controlled Components in React?

In HTML, form elements like input, textarea, and select maintain their own state and update automatically based on user input.

In React, a Controlled Component is a form element whose value is controlled by React state instead of the DOM. The state is updated using the useState() Hook and changes are tracked using onChange or onSubmit handlers.

This gives developers better control over form data and allows validation, formatting, and real-time updates.

📌 What is a Controlled Component?

  • Form elements are controlled by React state, not by the DOM
  • Data flows from the input → to state → back to input
  • Changes are handled using onChange
  • State is updated using useState()

⚙️ Example – onChange Handler

The input value is managed by useState and updated on every onChange event. You can transform the data (e.g., uppercase, limit length, replace characters).

React Playground
import React, { createContext } from 'react';
import ControlledForm from './ControlledForm.jsx';
const App = () => {
  return (
    <div>
      <ControlledForm/>
    </div>
  );
}

export default App;

📤 Example – onSubmit Handler

Use onSubmit to capture data when the form is submitted. Prevent the default refresh using e.preventDefault().

React Playground
import React, { createContext } from 'react';
import ControlledForm from './ControlledForm.jsx';
const App = () => {
  return (
    <div>
      <ControlledForm/>
    </div>
  );
}

export default App;

📝 Handling Multiple Input Fields

You can manage multiple inputs by storing them in a single state object. Use name attribute and update the respective property dynamically.

React Playground
import React, { createContext } from 'react';
import FunctionInput from './FunctionInput.jsx';
const App = () => {
  return (
    <div>
      <FunctionInput/>
    </div>
  );
}

export default App;

📦 Handling TextArea, Dropdown, and Checkbox

Other form elements like textarea, select, and checkbox can also be controlled using useState().

React Playground
import React, { createContext } from 'react';
import OtherInput from './OtherInput.jsx';
const App = () => {
  return (
    <div>
      <OtherInput/>
    </div>
  );
}

export default App;

🍎 Handling Multiple Checkboxes

Store selected values in an array and update it dynamically when checkboxes are checked or unchecked.

React Playground
import React, { createContext } from 'react';
import MultipleChecks from './MultipleChecks.jsx';
const App = () => {
  return (
    <div>
      <MultipleChecks/>
    </div>
  );
}

export default App;

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - Uncontrolled Components