JavaScript FrameworksReact

Controlled Component in React Forms

Form controls in React come in two types: Controlled Component and Uncontrolled Component. In this video, we will focus only on the Controlled Component.

In a Controlled Component, the “single source of truth” (data) is maintained in the React state property.    An input form element whose value is controlled by React in this way is called a “controlled component”.

In HTML, form elements such as <input><textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().

In a Controlled Component, form data is handled by a React component using an event handler (e.g. handleChange) for every state update.  Since handleChange runs on every keystroke to update the React state, the displayed value will update as the user types.  This makes it straightforward to modify or validate user input. The following example illustrates this explanation.

Source code for demo in the video

JSX

Verified by MonsterInsights