React Forms

React Forms

  • In Websites, Forms are an integral part of any modern web application.
  • Form allows the users to interact with the application as well as gather information from the users.
  • In Websites, Forms can perform many tasks that depend on the nature of your business requirements and logic such as authentication of the user, adding user, searching, filtering, booking, ordering, etc.
  • In Websites, a form can contain text fields, buttons, checkbox, radio button, etc
  • In Websites, the form has the default HTML form behavior of browsing to a new page when the user submits the form.
  • If you want this behavior in React, it just works.
  • But in most cases, it’s convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form.
  • In React JS, the standard way to achieve this is with a technique called “controlled components”.
  • HTML form elements work a bit differently from other DOM elements in React, because form elements naturally keep some internal state.
  • In React JS, state is typically kept in the state property of components, and only updated with setState().
  • In React JS, we can use useState() Hook in functional components with react forms.

Handling Forms

  • Handling forms is about how you handle the data when it changes value or gets submitted.
  • In HTML, form data is usually handled by the DOM.
  • In React, form data is usually handled by the components.
  • When the data is handled by the components, all the data is stored in the component state.
  • You can control changes by adding event handlers in the onChange attribute.

Creating Form

  • React offers a stateful, reactive approach to build a form.
  • The component rather than the DOM usually handles the React form.
  • In React, the form is usually implemented by using controlled components.
  • There are mainly two types of form input in React.
    • Controlled component
    • Uncontrolled component

Controlled Component In React

  • In HTML, form elements typically maintain their own state and update it according to the user input.
  • In the controlled component, the input form element is handled by the component rather than the DOM.
  • Here, the mutable state is kept in the state property and will be updated only with setState() method.
  • Controlled components have functions that govern the data passing into them on every onChange event, rather than grabbing the data only once, e.g., when you click a submit button.
  • This data is then saved to state and updated with setState() method or useState() Hook. This makes component have better control over the form elements and data.

Controlled Components With Function & useState

No responses yet

Leave a Reply

Your email address will not be published.