Handling forms in React
Tags: react, javascript, forms, tutorial
Published: 2020-10-19 07:06:38

---
title: Handling forms in React
published: true
description: 
tags: React, Javascript, Forms, tutorial
---
As a web developer, you have probably interacted with HTML [forms](https://www.w3schools.com/html/html_forms.asp). 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](https://reactjs.org/). This article assumes that you have basic knowledge of  [ReactJs](https://reactjs.org/tutorial/tutorial.html) and  [React Hooks](https://reactjs.org/docs/hooks-intro.html). 

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

## Introduction to React Forms
Basically, ReactJs has two types of form elements,  [controlled](https://reactjs.org/docs/forms.html#controlled-components) and  [uncontrolled](https://reactjs.org/docs/uncontrolled-components.html). 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](https://www.w3schools.com/js/js_htmldom.asp) 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1602945331382/C6oTByOqv.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](https://kentcdodds.com/blog/application-state-management-with-react) article by Kent C. Dodds who explains it in a very simple manner. 
In this article, we will be using the  [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook to store the various user details.

![carbon.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1602949223390/qrw1i4U0B.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](https://github.com/r0b0tt/react-form-handling).

![input.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1602949827399/9SKrfbbui.png)

![select.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1602949832786/QseaWUwNP.png)

![checkbox.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1602949944834/ixV6ZD9ZI.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](https://www.w3schools.com/tags/att_name.asp#:~:text=The%20name%20attribute%20specifies%20a,to%20target%20a%20form%20submission).

After converting our elements to controlled components, we can now implement our `onchange` handler. An  [onchange](https://www.w3schools.com/jsref/event_onchange.asp) 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1602951420473/OOZdnr1Hd.png)
Our `handleInputChange` function takes the `onchange` event as a parameter. We then use object  [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) method and remove it from the array using the  [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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](https://www.w3schools.com/jsref/event_onsubmit.asp) 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1602951999012/qjtuHO_fA.png)

Then we implement the function we have passed.
![carbon (8).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1602952186992/MsDyVacKX.png)

In our function above, we prevent the default behaviour when our form is submitted using the  [preventDefault](https://www.w3schools.com/jsref/event_preventdefault.asp) 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.