Reading 37 - AvreyBrown-401-advanced-javascript/seattle-javascript-401d32 GitHub Wiki
- React offers a stateful, reactive approach to building forms. Unlike other DOM elements, HTML form elements work differently in React. The form data, for instance, 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.
- Callback functions are 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's composition model lets you organize your React components into smaller reusable code. Each component exists as an independent functional unit and an hierarchy of components can be used to represent a specific feature. This structure works particularly well with forms. You can create custom components for , <textarea>, , etc. and reuse them to compose a FormContainer component.
-
Note: although it could be tempting to use a form library instead, chances are high that you might come across obstacles when you need to add custom behavior and validation. Creating a reusable form component from scratch will help you bolster your understanding of React forms.