”;
Forms are a common part of web applications which are mainly used allow users to interact with the application. These forms maybe included on the web page to gather information of the user, to let the user search a website, to make payments etc. The basic elements a form can contain are input fields, buttons, checklists, drop-down menus and so on. The data obtained from these forms is usually handled by components in React.
To learn how to use forms in React, let us look at some examples.
Form Programming
Unlike HTML where forms get updated based on user input data, React updates the form with the help of its state. The mutable state is typically specified in the state property of components, and is only updated using setState().
The nature of form programming needs the state to be maintained. Because, the input field information will get changed as the user interacts with the form. But as we learned earlier, React library does not store or maintain any state information by itself and component has to use state management API to manage state. Considering this, React provides two types of components to support form programming.
-
Controlled component − In controlled component, React provides a special attribute, value for all input elements and controls the input elements. The value attribute can be used to get and set the value of the input element. It has to be in sync with state of the component.
-
Uncontrolled component − In uncontrolled component, React provides minimal support for form programming. It has to use Ref concept (another react concept to get a DOM element in the React component during runtime) to do the form programming.
Let us learn the form programming using controlled as well as uncontrolled component in this chapter.
”;