Yogesh Chauhan's Blog

What are Controlled Components in React?

in React on May 12, 2021

Standard HTML form elements and React DOM elements work a bit differently.

Controlled Components

In React, when handling a form, you’d want a JavaScript function that handles the submission of the form. The function will have access to the form data entered by the user. This technique is called “controlled components”.

How forms are handled in HTML and React?

HTML form elements maintain their own state and update the state based on the user inputs.

In React, it’s a bit different. React keeps a mutable state of components and it gets updated using setState().

How to create a controlled component?

Creating controlled component requires you to combine both HTML and React handling of form elements and making the React state as the controller. So, the same React component that renders the form elements has now more control over those elements and it can control what happens inside those form elements.

A Controlled Component is nothing but a technique of controlling the value of form input elements by Recat.

React simple form example

As you can see in the example above, we are setting the value of input element as this.state.value and the state of the input element will keep changing on user input. Hence, we can have access to the current value way before user submits the value.

The handleChange will keep the React state updated. You can actually type something and see the console logging the most recent value every single time.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Configuring Modules with @forward rule in SCSS (Sass)SCSSSQL ALL OperatorSQL/MySQLHow to Find the Highest (or Lowest) Number in an Array in JavaScript?JavaScriptHow to concatenate variable with string in Swift?SwiftHow to enable and disable button using JavaScript?JavaScript2 Ways We Can Write Multiple Line Commands in PHPPHP