Tutorial to setting up forms in React

React is THE most popular UI library right now. And for a good reason, it allows you to implement a lot of great UX features.

In this article, we’ll talk about using React to implement forms, and common features like form validation. Forms are important for collecting user inputs. Fortunately, React ecosystem gives you everything you might need to successfully collect user inputs.

First off, you should know that React recommends to developers to use controlled components. These are input elements that get their value from the state, but also user’s inputs are stored in the state. In a way, React input elements are simply intermediaries between state and user interface. They don’t have a state of their own. This provides many benefits. One of those benefits is the ability to do easy form validation.

To do form validation in React, you can simply access current value for a certain input field. State object is a JavaScript object, so you can write functions to make sure it meets certain standards. For example, to make sure that user’s email contains the ‘@’ sign. Or you can check values against a regular expression. Possibilities are endless.

It’s even better that JSX allows you to conditionally display some elements. That way, you can display error messages only when user entered an incorrect value. You can even use conditional inline styles to change the color of the message. Possibilities are endless.

Next thing you can do is clear each field of the form after it is submitted. This is another great UX feature. It is especially important if the user is going to enter values into the field multiple times over. They shouldn’t have to clear the input field themselves. It’s simply bad UX.

Once again, storing input values in the state really helps. You can simply modify the handler for the submit event. So, when the form is submitted, the function automatically sets all input values to an empty string. Because individual elements’ values are tied to the state, the fields will be empty once again. Check out this guide for an example of how to reset form after submit in React.

If your form submits data to the server, you’ll need to implement that in the onSubmit function. It’s the event handler that runs every time user submits a form. In React, onSubmit is set on the <form> element itself. It’s only executed if the form element contains a submit button, with a type of ‘submit’.

Also, when implementing form in React, you’ll need pairs of <label> and <input> elements. In html, you use the for attribute to specify which label corresponds to which input. Since JSX is essentially JavaScript that looks like HTML, you can’t use the for attribute. You should use htmlFor instead.