YogeshChauhan . com

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.

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to change CSS with jQuery?CSSWhat’s a repository on Github?MiscContent types in DrupalDrupal3 Ways we can create URLSearchParams Objects in JavaScriptJavaScriptPHP Variables ScopePHPFor In Loop in Swift for BeginnersSwift