Codementor Events

Detailed Article on How to Create Forms in React from Scratch!

Published Jun 08, 2021
Detailed Article on How to Create Forms in React from Scratch!

We will make use of hooks provided by React to manage state in the React forms.

Note — Some prior React knowledge is required to understand this completely.

First of all, we will use basic HTML for creating input and label the fields.

1_qSEfXDoKCo_2SGbi5KaMFQ.png

The basic form structure is set up and will look like this.

1_8X0KRgjfX-vx9liHZmOTRw.png

So, after the forms are set up, we will make them functional and add functionalities like validation, etc.
We will use two useState hooks to store the data being entered in the form fields, and initiate the enteredName and enteredEmail with blank default values.
1_jIcVYQrVRNS9JMQmY4ROlw.png

To update the enteredName and enteredEmail values, we will use onChange(so that the state changes with every keystroke change in the input field) in the input and update the state accordingly as shown below.

1_sPQT0g8v81L5Gwvu6WdHIg.png

For adding two-way binding, so that we can explicitly change the input field when the state changes, we will use the value property of the input HTML tag to adjust the value in the input. This is to ensure that when we submit the form, the form values revert to blank.

1_Sava15Ni2DlsnMoiyTQXDg.png

The emailChangeHandler and the nameChangeHandler function will implicitly (on their own) receive an event (denoted as ‘e’, you can use any variable name as the argument, but ‘e’ is usually the convention) object as an argument which will have the value entered in the input field. And this function will be fired automatically whenever the input data changes.

1_GrwCOp9N692_ZM9zgDN5Cw.png

Now we have the state i.e. the enteredName and enteredEmail changing as the input data in the form changes.

Half the work is done at this point. Now we will take care of the validation part of the form. By validation, I mean to validate the data and show the users that valid information is being entered. For example, the email should contain “@” and “.com” for the email field in the form to be valid.

Validation is higher level code, so try to understand it carefully.
So, the onBlur event is available with the input HTML tags which will trigger whenever we click on the form and then click somewhere else.
Using the onBlur event, we can display the error message to the user if they have entered something invalid.

1_bMHbq6zsm3SGdWvYfqbfEg.png

Now, since the onBlur event is set up, we will have a look at the functions that will be fired when this event will occur.

We will have to store whether the user has touched or entered something into the form or not. As for the first time, we cannot display or validate as the user has not entered anything. But then onwards, whenever the user tries to type something, then we need to validate.

So, by default, we set the enteredNameTouched and enteredEmailTouched to false for the initial loading of the form.

1_XJW4XpBcHE2gKoLgNAgTTg.png

Whenever we write something and then click outside the input field, the onBlur event will fire the nameTouchHandler and emailTouchHandler and set their values to true so that we know that the user has entered something and we should validate the input.

1_7Va9xwA3DSe0HfJt1iSGSw.png

Now, we know that the user has entered something in the input fields and it is the time to validate the data.
For that, we will set formValid = “false” for the initial page load.

1_WbiHceeOBwPG3Xk3csRe9A.png

Now, to validate the input, we will check the data which was entered in the input field of the form. But to display an error message to the user, we should bear in mind that we should not display an error message the first time the form loads.

So, for that, we have to check 2 conditions —
1)The form must be touched (formTouched set to “true”).
2)The data entered in the form must be invalid.
For checking these 2 we will use -

1_MVASx2Rls-sZWAMV2vOhkQ.png

So, when we want to dynamically display whether the user data entered into the input fields is valid or not, we will use enteredNameTouchedInvalid and enteredEmailTouchedInvalid which will ensure that both the above conditions are checked before displaying the error message.

1_XwzKenwlSS0WSbcDNP_qQQ.png

Now, since the input field message is displayed, we also want the form color to change to red when the data is invalid. So, we will dynamically change the classes applied to the form when the data is invalid.

1_qHme24kBzg0VuVQn0xInww.png

1_yXw65gpewye5ZIL3qBCDsQ (1).png

So, the form will look like this when entered data is invalid.

1_4SUtJO4bYjoYncN1cPibnA.png

Now, the form has been dynamically validated. Also it displays an error message when the data entered is incorrect (You can have your own checks for validating data; I have used length-check for name, and “@” and “.com” checks for the email; you can also use Regex expressions for implementing more tedious checks).

In the end, when we submit the form, we have to ensure that the form input data is reset to blank. For that, we have to reset the value of enteredName and enteredEmail to blank.

1_5AIKAMMr5zE9_Y-dUIzjKg.png

When the submit button will be clicked, the onSubmitHandler function will be fired.
As mentioned earlier, we will receive an event object implicitly with this event and the function will look like this

1_Wn5WY4Pjtsejsa3axCmLKQ (1).png

We will check if the form is valid or not, and for checking whether the form valid or not, we will be using this.

1_9jwqx_xPCZ3I91NEEfgx6Q.png

Now, if the form data is invalid, we will simply return which terminates the further execution of the function.
But if the data is valid, then we will have to reset the input data fields to blank and emailTouched and nameTouched to false. So that form comes back to its initial state after being submitted.

And that’s it. Hope you found this article helpful and can now go ahead in creating and validating your own React forms. Thank you!.

Discover and read more posts from Pulkit Sharma
get started
post commentsBe the first to share your opinion
Show more replies