Handling forms in React

r0b0tt

Antonio Maina

Posted on October 19, 2020

Handling forms in React

As a web developer, you have probably interacted with HTML forms. Forms provide an interface for us to collect data from users and then perform various actions using that data. For example, a signup form collects registration data such as email, name and password from users and creates accounts for them.

In this article, we will learn how to handle forms using ReactJs. This article assumes that you have basic knowledge of ReactJs and React Hooks.

Here is the source code for this article. https://github.com/r0b0tt/react-form-handling.

Introduction to React Forms

Basically, ReactJs has two types of form elements, controlled and uncontrolled. According to the official documentation, controlled elements control their own state and update them based on user input. Uncontrolled elements, on the other hand, rely on the DOM to handle the form data. The recommended way, however, is to use controlled components.

Form Setup

For this article, we will be building a basic registration form for a careers website. Here is the final design.
localhost_3000_.png

Handling Form Input

Whenever a user enters information in our form elements' fields, we need to store it in some sort of state. If you're unfamiliar with state management in ReactJs you can checkout out this article by Kent C. Dodds who explains it in a very simple manner.
In this article, we will be using the useState hook to store the various user details.

carbon.png
From the image above, you can see that we have stored all registration details using the useState hook. We have initialized some fields so as to give default values to some of the form elements. After setting up our state, we can now get user input from our form elements and store it in our userDetails state.

Right now, our form elements are uncontrolled components and we need to convert them to controlled components. We do this by adding the value and onChange properties to the elements. The images below show how we add the attributes to the input, select and checkbox elements respectively. Note that the values are being fetched from our userDetails state. You can view the other elements in the source code.

input.png

select.png

checkbox.png

As you might have noticed, we have added an extra attribute on the checkbox elements called checked. This attribute is used to set the checked state of the checkbox. In our case, it checks whether the current value exists in our opportunities array that is in our userDetails state. Another important attribute here is the name attribute. It is used to reference that particular element. You can learn more about it here.

After converting our elements to controlled components, we can now implement our onchange handler. An onchange event occurs when the value of an element is changed. ReactJs exposes an onChange property on all form elements whereby we pass a function to handle input change.
Here is the function we have implemented.
handleInputChange.png
Our handleInputChange function takes the onchange event as a parameter. We then use object destructuring to get the name and value of the current form element from the onchange event.

The default behaviour will be to update our state using the setUserDetails function exposed by our useState hook. As you might have noticed, the name attributes of our form elements match the keys in our userDetails state. This allows easy and seamless updating of our state using the spread operator.

One special case here is our opportunities' checkbox elements. We have three values namely contract, partTime and fullTime. We have hardcoded these values to the elements.

In this case, we check whether the current checkbox is checked. If so, we add its value to our opportunities array, else, we find its index in the opportunities array using the findIndex method and remove it from the array using the splice method. Finally, we use the spread operator to update our state with the new opportunities selected.
In our checkbox elements, we display the checked status by checking whether the value of the checkbox is contained in our opportunities array using the includes method.

Handling Form Submission

After storing user input from our registration form, we should now handle what happens when the user clicks the create account button.

When the user clicks the button, the form details are submitted. This emits an onsubmit event from the form. We will implement a function to handle our form submission.

First of all, we add the onSubmit attribute exposed by ReactJs to our form element.
carbon (7).png

Then we implement the function we have passed.
carbon (8).png

In our function above, we prevent the default behaviour when our form is submitted using the preventDefault method and then log our user details to the console.

In real-life scenarios, you would probably send the data to your servers so as to create that users account.


I hope this article was educative.

💖 💪 🙅 🚩
r0b0tt
Antonio Maina

Posted on October 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Handling forms in React
react Handling forms in React

October 19, 2020