Getting started with forms in React
Tags: react, webdev, beginners
Published: 2020-05-11 05:31:53

---
title: Getting started with forms in React
published: true
description: A guide on fetching values and handling change events on forms in React
tags: react, webdev, beginner
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/d5yy8o9zc0gvb4n1q3f1.jpg
---

## Overview

Forms are an essential way of how users get to interact with software applications. Form elements facilitate operations such as collecting data and enabling the control of a user interface e.g displaying alerts, viewing menu items, interacting with dialog boxes, etc. This tutorial will guide you on the steps one takes to collect data from form fields using React.

The form elements we are going to look at are:
1. **input** - _creates form controls to collect user data_
2. **select** - _provides a list of predefined menu options_
3. **option** - _represents an item on a select or datalist element_

## Introduction

Form elements typically consist of various attributes that facilitate the process of collecting and manipulating data. Some of the attributes on the form elements include:

1. id - _gives a unique identifier for the form field_
2. type - _identifies the input category_
2. name - _defines the title the form field will be identified by_
3. value - _specifies the initial value_

## Listening to form events

There are a number of events that are triggered by the actions of users when interacting with forms. The **change** event is the event type we are going to listen to. This event is triggered when the value of a form element has been altered by a user. In order to tap into the **change** event, we provide our own custom event handling function which is mapped to the **onchange** property. This function has the following signature:

{% gist https://gist.github.com/khwilo/ef2cf0d4ec7d49b5d1f93ca8eb0f7f25 %}

The event parameter on the event handling function is a wrapper around the browser native event. This **event** is an object which contains various properties one of which is the **target**. The **target** property refers to the object in which an event was dispatched.

For example, if the email input field dispatched the **change** event then it will be the target. This means that we can access the values of the attributes that are attached to the input field. In JavaScript we can store the values in variables as follows:

{% gist https://gist.github.com/khwilo/1c2516576fc2ebac29017963bbce97b1 %}

## Handling form data

We need to determine the structure of the data that a user will be able to use on our form. In this guide, we are going to use the following definitions to store the form data.

- username - _text_
- age - _number_
- email - _text_
- password - _text_
- languages - _an array of objects_
- industry - _text_
- country - _text_

Now that we have laid out the structure of the data we are going to collect from the users, we need to define the structure in code and also determine how to store the data.

{% gist https://gist.github.com/khwilo/47d8031223b2dafb4eadaa04b7bf6fec %}

Note that 'languages' is a property that represents the checkbox values. When fetching values from the checkbox elements the values are sent as key, value pairs. That is why the property is defined as an array of objects. The attributes of the checkbox are already defined as options one can choose from. The field property represents the radio button value.

For state management purposes, the form values are stored as an object. The initial value is provided so that on the first render, the fields are not _undefined_ and thus satisfy that we are able to maintain our own state and update it as desired.

We will utilize the use of the React __useState__ hook which gives us the capability to add state to our functional component:

{% gist https://gist.github.com/khwilo/736eebf70e5896287e9310dc211a0066 %}

Now that we have defined the initial state variable and its values, we can create the form elements. The username, age, email, and password input fields are defined in code as follows.

{% gist https://gist.github.com/khwilo/138d33564abb0a037945b20d74ef25d6 %}

The attributes of the input fields are mapped to their respective **formValues** object property. It is important to note that for each input field, we provide an **onchange** property with an event handler function. The provided event handler function, **handleChange** has not been defined yet (_It will be defined later_). For every form field that provides a value attribute, an _onchange_ event handler function is required, otherwise, the form field will be a _readonly_ field.

The event handler function requires that an event parameter is passed to it. This function is where we will update the **formValues** state by getting the name and value of the target form element that the **change** event has been fired and placing them as key, value pairs in the **formValues** object.

{% gist https://gist.github.com/khwilo/3c9b015df4fe4f719ec8b78308cbcfe9 %}

The 'industry' field is an option where one can choose from a collection of radio button values. In order to get the given field value a user has selected, we set the checked attribute of the radio button to the result of calculating the comparison of the radio button state value (_in our case it will be **formValue.industry**_) to a given value of the same name. If the expression evaluates to true, then the checked property will be true otherwise it will be false. 

{% gist https://gist.github.com/khwilo/72ce77fb80ee89ff49ea4d86b4d3662e %}

The languages will be represented as checkbox elements:

{% gist https://gist.github.com/khwilo/3b039662e05b25f952e600a02e2a0ca6 %}

The 'languages' property contains an array of objects. These objects represent the various checkbox elements' field attributes. Since the checkbox elements are stored in an array,  we need to check if the input field is a checkbox before updating its state. If the input field is a checkbox, fetch the reference to the languages state property and create a new array of language objects by looping through all the properties in the languages array to see if the language's value property is the same as the one on the `event.target.value`. Later, set its isChecked property to the checked value of `event.target.checked`. Then, update the formValues state with appropriate values.

{% gist https://gist.github.com/khwilo/228f50f70172cd9b0698790b1da2e245 %}

The country field represents one of an individual option in a select element. The select element expects a name, id, value, and an onChange event handler.

{% gist https://gist.github.com/khwilo/e61ae9b8518662f977b6932e327b00fe %}

The logic to handle the event for the select element is the same as the one for the inputs of type name, age, email, and password defined earlier. On the first render, the country value will be set to an empty string. When selecting a given option the country value will be updated to match the value of the option field. 

## Conclusion

We have now completed implementing the logic for working with forms in React. There are various improvements to be done on the form. For instance, refactoring the code and putting the various form elements in their own respective components. To view the complete code with the refactoring done, you can check out this repository:

{% github https://github.com/khwilo/react-forms-demo %}