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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to change style of nth-child using jQuery?jQueryHow to remove N/A from Radio Button list in Drupal?DrupalHow to get query string values in JavaScript? (URL Manipulation using URLSearchParams)JavaScriptIs Software Really Eating The World? I don’t think soMiscellaneousHow to Install PHP composer in Mac OS Catalina?PHPWordPress: How to print ACF repeater field values?WordPress