Wednesday, October 26, 2022

14/365: Controlled Vs Uncontrolled Forms

 Forms are everywhere on the web. Whenever a website or an app needs information from a user, a form is used. Even this post right now is being submitted through a form. In React there are two kinds of forms: controlled and uncontrolled. 

Uncontrolled forms 

The uncontrolled form is simple, and is best use for basic inputs. Uncontrolled forms are submitted, and their value is read using the useRef hook, which retrieves whatever was inputted into the form upon submission. This is more analogues to a traditional HTML form. 

Controlled Forms

A controlled form, however, makes use of React state and the "value" prop along with an "onChange" callback function to listen to the form and dynamically update the state as information is typed. This is much more powerful and allows the developer to program whole suites of functionality into the app with forms. For example, I am sure you have used websites before where you sign up and you need to input a username, a password, and confirm the password. The submission button will be inactive unless all three fields are filled in properly, and the webpage will tell you when the passwords don't match. All this is possible because the values of the controlled components are being read and pushed into the state.

No comments:

Post a Comment

190: Sablier

 The CodeHawks platform has an upcoming audit on the Sablier protocol, so I decided to read through the docs and familiarize myself with the...