Forms are one of the few HTML elements that are interactive by default.

They were designed to allow the user to interact with a page.

Common uses of forms?

  • Search
  • Contact forms
  • Shopping carts checkout
  • Login and registration
  • and more!

Using React we can make our forms much more interactive and less static.

There are two main ways of handling forms in React, which differ on a fundamental level: how data is managed.

  • if the data is handled by the DOM, we call them uncontrolled components
  • if the data is handled by the components we call them controlled components

As you can imagine, controlled components are what you will use most of the time. The component state is the single source of truth, rather than the DOM. But sometimes you are forced to use uncontroller components, for example when using some form fields that are inherently uncontrolled because of their behavior, like the <input type=”file”> field.

When an element state changes in a form field managed by a component, we track it using the onChange attribute.

With class components, in order to set the new state, we must bind this to the handleChange method, otherwise, this is not accessible from within that method:

Similarly, we use the onSubmit attribute on the form to call the handleSubmit method when the form is submitted:

Using hooks it’s all much simpler:

Validation in a form can be handled in the handleChange method: you have access to the old value of the state and the new one. You can check the new value and if not valid reject the updated value (and communicate it in some way to the user).

HTML Forms are inconsistent. They have a long history, and it shows. React however makes things more consistent for us, and you can get (and update) fields using its valueattribute.

Here’s a textarea, for example:

The same goes for the select tag:

Previously we mentioned the <input type=”file”> field. That works a bit differently.

In this case you need to get a reference to the field by assigning the ref attribute to a property defined in the constructor with React.createRef(), and use that to get the value of it in the submit handler:

This is the uncontrolled components way. The state is stored in the DOM rather than in the component state (notice we used this.curriculum to access the uploaded file, and have not touched the state.

I know what you’re thinking — beyond those basics, there must be a library that simplifies all this form handling stuff and automates validation, error handling and more, right? There is a great one, Formik.

I create easy to digest Front-end related articles here.Yo'll find me writing about everything from JavaScript basics,to larger framework and library tutorials.