reactjs-component-lifecircle

In React, a component’s internal state is kept to minimum because every time the state changes, the component is rendered again. The purpose of this is to have an accurate representation of the component state in your JavaScript code and let React keep the interface in sync.

For this reason, form components such as <input>, <textarea>, and <option> differ from their HTML counterparts because they can be mutated via user interactions.

React provides two ways of handling forms as components and lets you choose based on your app characteristics or personal preference. The two available ways to handle a form field are as a controlled component or an uncontrolled component.

Controlled Components

A form component with a value or checked prop is called a controlled component. In a controlled component, the value rendered inside the element will always reflect the value of the prop. By default the user won’t be able to change it.

Special Cases set value in React

Uncontrolled Components

Controlled components adhere to React’s principles and have their advantages. While uncontrolled components are an anti-pattern for how most other components are constructed in React, sometimes you don’t need to oversee the user input field by field.

This is especially true in longer forms, where you want to let the user fill in the fields and then process everything when the user is done.

If you want to set up an initial value for an uncontrolled form component, use the defaultValue prop instead of value, or defaultChecked in case of checkbox.

 

ReactJS: Working with form

Category: JavascriptProgramingReactJS
0
756 views

Join the discussion

Your email address will not be published. Required fields are marked *

Comment moderation is enabled. Your comment may take some time to appear.