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:
- input - creates form controls to collect user data
- select - provides a list of predefined menu options
- 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:
- id - gives a unique identifier for the form field
- type - identifies the input category
- name - defines the title the form field will be identified by
- 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:
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:
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.
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:
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.
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.
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.
The languages will be represented as checkbox elements:
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.
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.
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:
khwilo / react-forms-demo
Get started with working with forms in React
Get started with using forms in React
This repository contains code for my tutorial on working with forms in React. It's a high level overview on how one get started with handling events and data in forms. To find the tutorial for this project visit this link: Getting started with forms in React.
Top comments (2)
nice post. easy to read and understand
Thank you!