Nearby lessons

21 of 43

⚛️ 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).

Example03
Loading editor…

📤 Example – onSubmit Handler

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

Example04
Loading editor…

📝 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.

Example05
Loading editor…

📦 Handling TextArea, Dropdown, and Checkbox

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

Example06
Loading editor…

🍎 Handling Multiple Checkboxes

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

Example07
Loading editor…

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4