forked from muddledsignal/class
-
Notifications
You must be signed in to change notification settings - Fork 0
Dynamic Forms
Matthew McQuain edited this page Feb 16, 2019
·
2 revisions
- Forms are very important in modern applications.
- They are the way for users to interact with our app.
- Developers rely on forms for everything: securely logging in the user, searching and filtering the product list, booking a product, and building a cart, etc.
- More complex applications built for enterprises are usually more form-intensive, with the input fields spanning over multiple tabs. On top of that, we have to consider the validation logic that needs to be deployed.
- Unlike other DOM elements, HTML form elements work differently in React. EG: form data is usually handled by the component rather than the DOM, and is usually implemented using controlled components.
- The form’s structure is similar to those of the usual HTML forms. However, each input element gets a component of its own, which we call dumb components.
- The container component is responsible for maintaining the state. The difference is, we're using a callback function to handle form events and then using the container’s state to store the form data. This gives your component better control over the form control elements and the form data.
- The callback function is triggered on events, including change of form control values, or on form submission. The function then pushes the form values into the local state of the component and the data is then said to be controlled by the component. Because we are using the value attribute on the form element, the value displayed will be the value of this.state.value.
- There is another technique, popularly known as uncontrolled components, for creating input forms.
- This is more like traditional HTML forms because the input form data is stored inside the DOM and not within the component.
- Elements like and <textarea> maintain their own state, which they update when the input values change. You can query the DOM for the value of an input field using a ref.
- React recommends using controlled components over refs to implement forms. Refs offer a backdoor to the DOM, which might tempt you to use it to do things the jQuery way.
- Controlled components are more straightforward — the form data is handled by a React component.
- However, if you want to integrate React with a non-React project, or create a quick and easy form for some reason, you can use a ref.