Handling forms | Mastering React: An In-Depth Zero to Hero Video Series

Web Tech Talk
31 Mar 202313:09

Summary

TLDRIn this React JS tutorial, the instructor guides beginners through form handling in React from scratch. The video covers creating forms using Bootstrap for styling, capturing form data with useRef, and validating inputs based on requirements. It demonstrates how to prevent page refresh on submit, display error messages, and conditionally enable the submit button. The instructor also suggests a task to enhance the form by disabling the submit button until the form is valid and showing error messages dynamically.

Takeaways

  • πŸ˜€ The video is part of a React JS tutorial series aimed at beginners.
  • πŸ”‘ The focus of this video is on form handling in React, including creation, validation, and submission.
  • πŸ› οΈ The presenter uses Bootstrap for styling the form fields to enhance user experience.
  • πŸ“ Form handling in React can be managed without third-party packages by writing custom logic.
  • πŸ—οΈ The form creation process involves using HTML form elements and Bootstrap classes for layout and styling.
  • πŸ” Form validation is crucial and involves checking for required fields, email format, and user agreement to terms.
  • πŸ”— The video demonstrates using `useRef` for form field values and `useState` for managing error messages.
  • πŸ›‘ The `preventDefault` method is used to stop the default form submission behavior which refreshes the page.
  • πŸ“’ Error messages are displayed to users to indicate what fields need to be corrected.
  • πŸ”„ After successful form submission, the form fields are cleared, and error messages are reset.
  • πŸ’‘ The video ends with a challenge for viewers to enhance the form by disabling the submit button until the form is valid and displaying error messages dynamically.

Q & A

  • What is the main focus of the video series 'React JS - Zero to Hero'?

    -The main focus of the video series 'React JS - Zero to Hero' is to teach beginners how to learn React JS from scratch.

  • What was the topic covered in the last video of the series?

    -In the last video, the topic covered was how to invoke HTTP requests in React.

  • What are the three steps involved in form handling in React as mentioned in the video?

    -The three steps involved in form handling in React are form creation, form validation, and form submission.

  • Why does the instructor choose to use Bootstrap for styling the form fields?

    -The instructor chooses to use Bootstrap for styling the form fields because it allows for easy styling and is a widely used framework for front-end development.

  • What is the difference between using 'button' and 'submit' as the type for a button in a form?

    -A 'button' type is a generic button that can be used for various purposes with additional functionality added using JavaScript, while 'submit' type is specifically used to submit the form and has the default functionality of submitting the form data.

  • How does the instructor prevent the default behavior of form submission which is page refresh?

    -The instructor prevents the default behavior of form submission by using the 'preventDefault' method from the event object.

  • What is the purpose of using 'useRef' in the context of form handling in React?

    -In the context of form handling in React, 'useRef' is used to access the form fields' values without causing a re-render of the component.

  • What is the validation requirement for the email field as per the video?

    -The validation requirement for the email field is that it should be in a standard email format, which is checked using a regex pattern.

  • How does the instructor handle error messages in the form validation process?

    -The instructor handles error messages by maintaining state variables for each error message and displaying them next to the respective form fields when validation fails.

  • What is the final step the instructor takes after form submission in the video?

    -After form submission, the final step the instructor takes is to clear the form fields and reset any error messages.

  • What task does the instructor give to the viewers at the end of the video?

    -The task given to the viewers is to develop the same form with a disabled submit button that gets enabled only when the form is valid, and to display all error messages as the user interacts with the form fields.

Outlines

00:00

πŸ“š Introduction to Form Handling in React

This paragraph introduces the topic of form handling in React JS, aimed at beginners. The speaker explains the purpose of forms in collecting user data and the three-step process involved: form creation, validation, and submission. It contrasts form handling in React with other frameworks like Angular, which have separate modules for forms. The speaker demonstrates how to create a form using React and Bootstrap for styling, including various form elements like text fields, email, number fields, dropdowns, checkboxes, and buttons. The focus is on creating a functional form without third-party packages and using Bootstrap's styling capabilities.

05:01

πŸ” Form Validation and User Input in React

The second paragraph delves into the validation of form inputs in React. It discusses the use of useRef to access form field values and the importance of validating user input based on business requirements. The speaker outlines a simple validation scenario where certain fields are required, the email format is checked, and a checkbox must be checked for form submission. Error messages are displayed to the user, and states are used to manage these messages. The paragraph also covers the process of clearing error messages and ensuring that the form only submits when valid. The speaker tests the validation logic and discusses the importance of highlighting error fields and focusing on them for user convenience.

10:03

πŸš€ Form Submission and User Feedback

The final paragraph focuses on the form submission process and user feedback. It describes how to check the validity of the form before submission and how to handle the form data once the form is valid. The speaker demonstrates a simple form submission process that logs the form values to the console and clears the form fields after submission. Additionally, it discusses enhancing user experience by highlighting error fields and focusing on them. The speaker concludes by assigning a task to the viewers to create a form with a disabled submit button that only enables when the form is valid and displays error messages dynamically. The video ends with a call to action for viewers to like, subscribe, and support the channel.

Mindmap

Keywords

πŸ’‘React JS

React JS is a popular open-source JavaScript library used for building user interfaces, particularly for single-page applications. It is maintained by Facebook and a community of individual developers and companies. In the video, React JS is the main focus as the series is designed to teach beginners how to use React JS from scratch, with the script detailing various aspects of form handling within this framework.

πŸ’‘Form Handling

Form handling refers to the process of managing form data in web applications, including creating, validating, and submitting forms. In the context of the video, form handling is a crucial part of the tutorial where the instructor explains how to create, validate, and submit forms using React JS, highlighting the importance of this process in collecting and processing user data.

πŸ’‘HTTP Requests

HTTP (Hypertext Transfer Protocol) requests are messages sent from a client to a server to request access to a resource. In the script, it is mentioned that the previous video explained how to invoke HTTP requests in React, which is essential for sending data to a server when a form is submitted.

πŸ’‘Bootstrap

Bootstrap is a widely used open-source CSS framework that helps developers design responsive and mobile-first websites. In the video, Bootstrap is used to style form fields, demonstrating how it can be integrated with React JS to create visually appealing user interfaces.

πŸ’‘Form Validation

Form validation is the process of checking user input to ensure it meets certain criteria before it is processed or stored. In the video, form validation is a key step in the form handling process, with the instructor showing how to validate form fields such as full name, email, and department to ensure they are not left blank and meet specific format requirements.

πŸ’‘Event Handling

Event handling in web development refers to the way browsers respond to user actions, such as clicks or key presses. In the script, event handling is discussed in the context of adding functionality to buttons and form submissions, with examples like using onClick handlers to clear form fields or onSubmit handlers to prevent page refreshes.

πŸ’‘State Management

State management in React refers to the way components store and update their state. The script mentions the use of `useState` and `useRef` for managing form field values and error messages, illustrating how state management is integral to form handling in React applications.

πŸ’‘Regular Expressions (Regex)

Regular expressions, or regex, are patterns used to match character combinations in strings. In the video, regex is used to validate the email format, showing how it can be employed to ensure user input adheres to specific standards.

πŸ’‘Conditional Rendering

Conditional rendering in React allows components to render differently based on the state or props. The script discusses how error messages are conditionally rendered based on the validation status of form fields, demonstrating the dynamic nature of UI updates in React.

πŸ’‘Form Submission

Form submission is the process of sending form data from the client to the server. In the video, form submission is the final step in the form handling process, with the instructor explaining how to prevent the default page refresh behavior and instead handle the submission using JavaScript, potentially to invoke an API.

πŸ’‘Dynamic Class Names

Dynamic class names in React are used to conditionally apply CSS classes based on component state or props. The script describes how to dynamically add an error class to form fields that have validation errors, highlighting the interplay between React's state management and CSS styling.

Highlights

Introduction to the series and purpose: React JS for beginners, covering form handling in this video.

Forms are used to collect user data, which is then processed when submitted.

Form handling in React involves three main steps: creation, validation, and submission.

Difference between React and Angular: React requires custom code or third-party libraries for form handling.

Creating a form with Bootstrap for styling: Installed and imported Bootstrap for easy form design.

How to create form fields in React using JSX, including labels and inputs with Bootstrap classes.

Using different input types: text, email, number, dropdown, and checkbox.

Explanation of button types: submit for default form submission and button for custom behavior.

How to prevent the default form submission behavior using `event.preventDefault()`.

Difference between useState and useRef for handling form field values; useRef is suitable when UI updates aren't needed.

Basic form validation: Ensuring required fields are filled and validating email format using a regex pattern.

Showing error messages for validation and updating states dynamically to display these messages.

Adding focus and highlighting to fields with validation errors, improving user feedback.

Form reset functionality after successful submission, clearing both form fields and error messages.

Task for viewers: Disable submit button until the form is valid and display error messages in real time.

Transcripts

play00:00

Hi Friends

play00:04

Welcome back to React JS - Zero to Hero series.

play00:14

This series is for beginners who wants to learn React JS from Scratch.

play00:18

In the last video I have explained about how we can invoke HTTP requests in react.

play00:23

In this video I am going to explain about form handling in react

play00:27

Let's start.

play00:29

Forms are used to collect information from end users.

play00:32

When the user fills out a form and clicks the submit button, the form data will be sent

play00:37

for processing.

play00:38

Form handling is about how you handle the data when it changes value or gets submitted.

play00:43

Usually, we can divide the form handling into a 3 step process.

play00:47

Form creation, form validation and form submission.

play00:50

And, in frameworks like Angular, we have a separate module for handling forms.

play00:55

But in react, either we need to go for some third party npm packages or we can write our

play00:59

own logic.

play01:00

In this video, I am going to explain you how we can do form handling in react using our

play01:05

own code.

play01:06

For that I have created a react application.

play01:08

I am going to use bootstrap, because using bootstrap we can easily style our form fields.

play01:13

To use bootstrap, I need to first install bootstrap.

play01:17

I can install bootstrap using this command.

play01:23

Now, bootstrap is installed inside node modules and so we can use this bootstrap dot css.

play01:33

Let me import the bootstrap dot css in index dot js.

play01:42

In app dot js, I am just having a h2 tag and then a div which is having a class form container.

play01:48

And I have applied some CSS.

play01:51

Let me start the server.

play01:54

Now we can see this.

play01:56

Ok, like I told before, our first step is going to be form creation.

play02:01

So, let me introduce a form element.

play02:03

Inside that, I am going to create our first field.

play02:07

In bootstrap, we have a class called form group, which can be used to group the form

play02:12

fields like label and input box.

play02:14

So, first let me create a div with class name as form group and then inside that let me

play02:19

create a label.

play02:21

Please note that, in JSX we have to use htmlFor instead of for.

play02:28

And then, let me create an input type text with an id.

play02:35

To this, I can add the bootstrap class name form control.

play02:39

Ok, our first field is ready.

play02:41

Let me quickly create another field for email, another number field for age, a dropdown for

play02:54

department and a checkbox.

play03:11

For checkbox alone, we need to have a little bit different structure.

play03:15

I have added this to style it correctly.

play03:21

Finally a submit button of type submit.

play03:24

I have a question here, can you think why I am saying that we need to create a button

play03:28

of type submit.

play03:30

Why not a button of type button.

play03:33

A button is just that, a button, to which we can add additional functionality using

play03:37

Javascript.

play03:38

In the mean time, a submit input type has the default functionality of submitting the

play03:42

form.

play03:43

Let me create another button, let it be of type button.

play03:47

I am going to use this button to clear my form fields.

play03:50

So here also, instead of button I can use the type as reset.

play03:55

But I wanted to show you how we can reset our form manually and so let me keep this

play03:59

type as button.

play04:00

Ok, now if I click this button, nothing happens because there is no event added.

play04:06

Let me create a function and let me add that using an onClick handler.

play04:15

Now also, we are not seeing any difference.

play04:17

But if I have a console log inside this function, we can see that on clicking this button.

play04:23

Ok, let me click this button, now we can see a question mark is added in the URL, that

play04:29

means something has happened.

play04:31

Let me create a function and let me bind that to this form using an onSubmit handler.

play04:37

Now, if I have a console log, and click this button, we can only see the console message

play04:47

only for a fraction of second, because every time when we click the submit button, the

play04:51

page refreshes.

play04:52

That is the default behavior.

play04:55

But we can use the prevent default method from the event to change the default behavior.

play05:00

Like this.

play05:02

Now, if I click, we can see the page is not getting refreshed.

play05:05

Hope you understood.

play05:07

Ok, now we have created our form.

play05:10

Next step is to validate the input.

play05:12

For that first we need to find a way to get the values from the form fields.

play05:16

In react, we have already seen either we can use useState approach or useRef approach.

play05:20

For this demo, we are not going to change anything in the UI, based on the form fields,

play05:25

we are just going to collect the values and send for processing.

play05:29

To be more specific, we are just going to log those values in the console.

play05:32

That's it.

play05:34

So we don't want to go for useState approach.

play05:36

And so, let me create useRef for each field and then let me bind that to the respective

play05:46

form fields.

play05:52

Ok, now we can access these fields and their values.

play06:00

So, let's do form validation.

play06:03

For that I am going to create a separate function.

play06:06

Inside this function, Let me get the values of each field and let me store in some variables.

play06:11

Please note that for all input fields and dropdown I have used respective ref dot current

play06:15

dot value.

play06:17

But for checkbox, I have used ref dot current dot checked.

play06:21

This will give us true or false.

play06:24

Now we need to write some logic to validate the values based on our business requirement.

play06:29

Let me define our requirement.

play06:31

Let me keep it simple.

play06:33

Full name, email and department fields should be required.

play06:36

That means they cannot be left blank.

play06:38

And, email should be in a standard email format.

play06:41

Finally, user has to check this checkbox to submit the form.

play06:44

And, we are not going to test all the negative scenarios like entering number in name field,

play06:49

etc.

play06:50

That will deviate us from learning the concept.

play06:52

Ok.

play06:53

And we need to show the error messages to the end user.

play06:56

For that we need to maintain few states.

play06:58

Let me create those.

play07:00

Initially, I am assigning them as empty string.

play07:03

And when there is an error, I am going to assign the respective error messages.

play07:07

For example, our first requirement is going to be full name is required.

play07:10

So, let me check whether full name dot trim is equal to empty string.

play07:15

If it is so, let me set the error message as Full name is required.

play07:20

And then, let me come to this form group and here let me add a span with class as error

play07:26

and let me show the message.

play07:28

Even for this error class, I have already added css.

play07:31

Ok, now we can call this function inside our handle submit function, so that we can test

play07:36

this validate form function.

play07:38

Ok, I am going to submit the form without any value.

play07:41

And so, we can see the error message.

play07:43

Similarly, let me do this for the email field.

play07:48

Ok, let's test.

play07:55

I am going to submit the form without entering any values.

play07:58

Now it is throwing error full name is required.

play08:00

Now, let me enter some value for full name and then submit, now the email is required

play08:06

error is showing but the full name error is not cleared.

play08:09

So what we can do, inside this block, we can reset the full name error.

play08:16

Now, we can see it is working.

play08:21

So we have to follow this approach for other fields as well.

play08:24

Ok, our next requirement is to validate whether the email is in valid format.

play08:29

For that, let me create a new function called validate email which accepts email as parameter

play08:35

and it test that against this regex pattern.

play08:37

This is the pattern for validating an email format.

play08:40

If the test is success, let me return true or otherwise let me return false.

play08:46

Now, I can call this function and let me pass the email.

play08:49

If this is going to fail, let me set the email is not valid error message.

play08:54

Here also, let me reset the full name error message.

play08:57

Now, let me test this.

play09:01

Ok, it is working.

play09:05

Let's move to the next requirement which is department should not be blank.

play09:09

This is similar to the full name requirement, let me copy this and modify according to our

play09:13

need.

play09:17

Finally, we need to validate whether the user has checked this checkbox or not.

play09:29

For that, I can simply check like this.

play09:31

If not agreed, I am clearing the department error and setting the agreed error as please

play09:36

agree with terms and conditions.

play09:40

Ok, let me test it.

play09:55

After the checkbox is also checked, we need to clear the agreed error message.

play09:59

And so, let me introduce an else block and let me clear the agreed error.

play10:02

Ok, let me test it once.

play10:10

It is working.

play10:11

Now, we need to proceed with form submission, if the form validation is success.

play10:16

For that, first let me declare a variable inside validate form function and let me initialize

play10:20

that as false.

play10:21

And, inside else block, let me change that to true.

play10:24

Finally let me return that variable.

play10:26

So, if the form validation is success, this method will return true otherwise false.

play10:31

So, in handle submit function, let me get that in a variable and let me check that variable

play10:37

and only when it is true, I am going to call another function called submit form.

play10:41

Let me also create the submit form function.

play10:43

Ideally, this is the function in which we can build our payload and invoke the API.

play10:49

But for now, let me console log the values of the form fields.

play10:52

Ok.

play10:53

Let's test it once.

play10:55

So, when the form is not valid, form is not getting submitted.

play10:59

And when the form is valid, we can see the console logs.

play11:04

That means the form is getting submitted.

play11:06

Ok.

play11:07

After the form is submitted, we need to clear the form fields.

play11:10

So, after this, let's call reset form function.

play11:13

And in reset form function, we can reset the form field values, like this.

play11:23

Also, we need to reset the error messages also.

play11:32

Let's test it once.

play11:35

Ok.

play11:37

It is working.

play11:39

It would be good if we highlight the field which is having error and focus that field

play11:43

as well.

play11:44

To highlight the field which is having error, we just need to dynamically add the class

play11:48

err.

play11:49

Which we can add it using the template string.

play11:50

Like this.

play11:51

I have already added CSS for this.

play12:01

And so, we can see the field having error is highlighted, both the color of the label

play12:05

and the border are changed to red.

play12:08

And to focus the field, we can use the respective ref dot current dot focus.

play12:23

Let me test it.

play12:30

It is working as expected.

play12:32

Hope you understood, how we can handle forms.

play12:34

Let me give you a task.

play12:36

You can develop the same form.

play12:38

But you can disable the submit button.

play12:40

You have to enable only when the form is valid.

play12:43

Also, display all the error message when user types or selects in the form field.

play12:48

Try this, if you need the solution code, you can get it from this repo.

play12:52

The link is also available in the description.

play12:55

That's all for today.

play12:56

Please like this video.

play12:58

Subscribe to my channel and support me.

play13:01

Thank you.

play13:03

Bye.

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
React JSForm HandlingValidationBootstrapJavaScriptWeb DevelopmentFrontendTutorialCodingEducational