{"id":6507,"date":"2021-06-21T09:53:24","date_gmt":"2021-06-21T09:53:24","guid":{"rendered":"https:\/\/programmingfields.com\/?p=6507"},"modified":"2026-05-02T06:29:33","modified_gmt":"2026-05-02T06:29:33","slug":"form-handling-in-react-js-with-validation-using-react-state","status":"publish","type":"post","link":"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/","title":{"rendered":"Form Handling in React JS With Validation Using React State"},"content":{"rendered":"\n<p>The form is a collection of inputs that collects the information from the user. For the form handling in React JS, you will have to understand the events. The events handling in React elements is very similar to handling events on DOM elements. You can write the same events inside React. But it allows writing the event name in the <strong>camelCase<\/strong> letter. While submitting a form you have to take care of the validation of every input. In HTML, the elements such as <strong>&lt;input&gt;<\/strong>, <strong>&lt;textarea&gt;<\/strong>, and<strong> &lt;select&gt;<\/strong> typically maintain their own state. These are called the controlled components. Actually, React has control over the controlled components to update their values. The state gets updated on the basis of user input. In this post, I will gonna show you the <strong>React form validation<\/strong> using state.<\/p>\n\n\n\n<p>Before moving to the <strong>React form validation<\/strong> functionality, let&#8217;s dive into the core of React JS. For the controlled component handling, React uses state.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-light-blue ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#What_is_React_State\" >What is React State<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Prerequisites\" >Prerequisites<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Create_a_React_App\" >Create a React App<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Create_Components_For_React_JS_Form_Validation\" >Create Components For React JS Form Validation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Create_Form_in_React_JS\" >Create Form in React JS<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Form_Handling_in_React_JS\" >Form Handling in React JS<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Explanation_of_React_Form_Handler\" >Explanation of React Form Handler<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#React_Form_Validation_Using_State\" >React Form Validation Using State<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Define_State_Object_For_Validation_Error_Message\" >Define State Object For Validation Error Message<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Create_Form_Validation_Rules\" >Create Form Validation Rules<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Display_Validation_Error_Message\" >Display Validation Error Message<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#React_Form_Submit_Result\" >React Form Submit Result<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Reset_Inputs_After_Form_Submit_in_React\" >Reset Inputs After Form Submit in React<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Use_of_Spread_Operator_%E2%80%A6_to_Hold_Previous_State\" >Use of Spread Operator (&#8230;) to Hold Previous State<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/programmingfields.com\/form-handling-in-react-js-with-validation-using-react-state\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_React_State\"><\/span><strong>What is React State<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The<strong> React state<\/strong> contains the property or data about the component. This is similar to <a rel=\"noreferrer noopener\" href=\"https:\/\/programmingfields.com\/crud-app-in-react-js-using-laravel-7-restful-api\/\" target=\"_blank\">React props<\/a>. The data or information can be set, updated, and reset. The state can be created and used inside the component. It is privately managed by the component itself. <\/p>\n\n\n\n<p>A component with the state is known as stateful components. To make the dynamic and interactive to the component, React state is very helpful.<\/p>\n\n\n\n<p>For the form handling and <strong>React form validation<\/strong>, I will use React state.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Prerequisites\"><\/span><strong>Prerequisites<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>I am assuming you are ready to create a new app in React JS. You should have the familiarty with the following-<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>React components,<\/strong><\/li><li><strong>React DOM,<\/strong><\/li><li><strong>Component rendering and,<\/strong><\/li><li><strong>React Router<\/strong><\/li><\/ul>\n\n\n\n<p>In my last post on React JS, I already covered these all. So, if you are a beginner then I recommend you to go through the last post on <a rel=\"noreferrer noopener\" href=\"https:\/\/programmingfields.com\/create-react-routing-in-react-js-using-react-router-dom\/\" target=\"_blank\">React Routing<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_a_React_App\"><\/span><strong>Create a React App<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For the form validation and components, I will be continue my previous React app. You might start by creating a new app in React JS by hitting the below command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">npx create-react-app blog<\/code><\/pre>\n\n\n\n<p>I have already created it, so not going to create another one.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img decoding=\"async\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-17-08-41-27.png?w=803&amp;ssl=1\" alt=\"React JS Installation\"\/><figcaption><strong>React JS Installation<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>Once, you are ready with the React app, let&#8217;s open it to the editor. Then start the development server.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img decoding=\"async\" src=\"https:\/\/i2.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-18-20-31-57.png?w=703&amp;ssl=1\" alt=\"React JS Homepage\"\/><figcaption><strong>React JS Homepage<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>For creating the form, you need the component.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/create-react-routing-in-react-js-using-react-router-dom\/\" target=\"_blank\" rel=\"noreferrer noopener\">Brief Overview of React Routing Using React Router DOM<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Components_For_React_JS_Form_Validation\"><\/span><strong>Create Components For React JS Form Validation<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In my last post, I have shown you everything from very scratch. I added <strong>Bootstrap 5<\/strong> for creating the Navigation bar in the header. We already created the following components-<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Header.js<\/strong><\/li><li><strong>Home.js<\/strong><\/li><li><strong>About.js<\/strong><\/li><li><strong>Contact.js<\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\"><strong>src<\/strong>\n  <strong>|__ components<\/strong>\n         <strong>|<\/strong>__ Header.js\n         |__ Home.js\n         |_<em>_<\/em> About.js\n         |__ Contact.js<\/code><\/pre>\n\n\n\n<p>Here, this the structure of created components we had.<\/p>\n\n\n\n<p>Now, I will extend the Contact component for creating the form. Then we will apply the form validation on the form. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Form_in_React_JS\"><\/span><strong>Create Form in React JS<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For the form designing, I will create a basic layout using <strong>Bootstrap 5<\/strong>. I am not going to design it much attractive. Before going to create the form, let me show the result of the activities in the last post. We already had the contact component.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img decoding=\"async\" src=\"https:\/\/i2.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-19-11-08-28-1.png?w=998&amp;ssl=1\" alt=\"Contact Component in React JS\"\/><figcaption><strong>Contact Component in React JS<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>In the above result, we have a title with heading element inside the Contact component.<\/p>\n\n\n\n<p>Now, let&#8217;s create a form here. So, firstly, open the <strong>Contact.js <\/strong>component file and put the below snippet.<\/p>\n\n\n\n<pre title=\"Contact.js\" class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">import React, {Component} from 'react';\n\nexport default class Contact extends Component {\n    render() { \n        return(\n            &lt;div className=\"container\"&gt;\n                &lt;div className=\"row justify-content-between pt-5\"&gt;\n                    &lt;div className=\"col-xl-6 col-lg-6 col-md-6 col-12 m-auto\"&gt;\n                        &lt;form&gt;\n                            &lt;div className=\"card shadow\"&gt;\n                                &lt;div className=\"card-header pt-3\"&gt;\n                                    &lt;h5 className=\"card-title\"&gt;Get in touch with us&lt;\/h5&gt;\n                                &lt;\/div&gt;\n\n                                &lt;div className=\"card-body px-4 py-4\"&gt;\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"text\" name=\"name\" placeholder=\"Name\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"email\" name=\"email\" placeholder=\"Email\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"password\" name=\"email\" placeholder=\"Password\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"text\" maxlength=\"10\" name=\"phone\" placeholder=\"Phone number\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"row\"&gt;\n                                        &lt;div className=\"form-group py-2\"&gt;\n                                            &lt;div className=\"col-xl-8\"&gt;\n                                                &lt;input type=\"radio\" value=\"Male\" name=\"gender\" className=\"mx-2\" \/&gt; Male\n                                                &lt;input type=\"radio\" value=\"Female\" name=\"gender\" className=\"mx-2\"\/&gt; Female\n                                                &lt;input type=\"radio\" value=\"Other\" name=\"gender\" className=\"mx-2\" \/&gt; Other\n                                            &lt;\/div&gt;\n                                        &lt;\/div&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"date\" name=\"dob\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;select defaultValue=\"\" name=\"city\" className=\"form-control\"&gt;\n                                            &lt;option disabled value=\"\"&gt;City&lt;\/option&gt;\n                                            &lt;option value=\"ranchi\"&gt;Ranchi&lt;\/option&gt;\n                                            &lt;option value=\"new delhi\"&gt;New Delhi&lt;\/option&gt;\n                                            &lt;option value=\"gurgaon\"&gt;Gurgaon&lt;\/option&gt;\n                                            &lt;option value=\"hyderabad\"&gt;Hyderabad&lt;\/option&gt;\n                                        &lt;\/select&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;textarea placeholder=\"About You\" name=\"about\" className=\"form-control\"&gt;&lt;\/textarea&gt;\n                                    &lt;\/div&gt;\n                                &lt;\/div&gt;\n\n                                &lt;div className=\"card-footer px-4\"&gt;\n                                    &lt;button type=\"submit\" className=\"btn btn-success\"&gt;Send&lt;\/button&gt;\n                                &lt;\/div&gt;\n                            &lt;\/div&gt;\n                        &lt;\/form&gt;\n                    &lt;\/div&gt;\n                &lt;\/div&gt;\n            &lt;\/div&gt;\n        );\n    }\n}<\/code><\/pre>\n\n\n\n<p>I have added the usable inputs for creating a basic form. Here, is the result of the above snippet.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1151\" height=\"701\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-06-39-25.png?resize=1151%2C701&#038;ssl=1\" alt=\"React Form Handling\" class=\"wp-image-6517\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-06-39-25.png?w=1151&amp;ssl=1 1151w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-06-39-25.png?resize=300%2C183&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-06-39-25.png?resize=1024%2C624&amp;ssl=1 1024w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-06-39-25.png?resize=768%2C468&amp;ssl=1 768w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption><strong>React Form Handling<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>Here, we have a basic form with some input elements. Now, we will see the <strong>form handling in React<\/strong>.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/create-a-todo-app-in-react-using-laravel-8-restful-apis\/\" target=\"_blank\" rel=\"noreferrer noopener\">Create a Todo App in React Using Laravel 8 RESTful APIs<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Form_Handling_in_React_JS\"><\/span><strong>Form Handling in React JS<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Like HTML, we cannot set the action attribute to submit the form. This will refresh the page. Here, we are in React, so, we need to handle the form without refreshing it. To achieve this, we will be using React events. Events in React are just like <strong>DOM events.<\/strong> It will work in the same way. But in React, the event naming is in <strong>camelCase<\/strong> letter.<\/p>\n\n\n\n<p>Before submitting the form in React, the first thing is to bind the input value to a variable. Here, we will have to create events for every input to get their respective value. Hence, <strong>React state<\/strong> will be used here to hold the value of every input.<\/p>\n\n\n\n<p>To submit a form, we have the <strong>onSubmit()<\/strong> event that will be used in the form element. So, let&#8217;s understand by going through the below code.<\/p>\n\n\n\n<pre title=\"Contact.js\" class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">import React, {Component} from 'react';\n\nexport default class Contact extends Component {\n    constructor(props) {\n        super(props);\n\n        this.state = {\n            name: '',\n            email: '',\n            password: '',\n            phone: '',\n            gender: '',\n            dob: '',\n            city: '',\n            about: ''\n        }\n    }\n\n\n    handleChange = (e) =&gt; {\n        this.setState({\n            [e.target.name]: e.target.value\n        });\n    }\n\n    handleSubmit = (e) =&gt; {\n        e.preventDefault();\n        console.log(this.state);\n    }\n\n\n    render() { \n        return(\n            &lt;div className=\"container\"&gt;\n                &lt;div className=\"row justify-content-between pt-5\"&gt;\n                    &lt;div className=\"col-xl-6 col-lg-6 col-md-6 col-12 m-auto\"&gt;\n                        &lt;form onSubmit={this.handleSubmit}&gt;\n                            &lt;div className=\"card shadow\"&gt;\n                                &lt;div className=\"card-header pt-3\"&gt;\n                                    &lt;h5 className=\"card-title\"&gt;Get in touch with us&lt;\/h5&gt;\n                                &lt;\/div&gt;\n\n                                &lt;div className=\"card-body px-4 py-4\"&gt;\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"text\" onChange={this.handleChange} name=\"name\" placeholder=\"Name\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"email\" onChange={this.handleChange} name=\"email\" placeholder=\"Email\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"password\" onChange={this.handleChange} name=\"email\" placeholder=\"Password\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"text\" onChange={this.handleChange} maxLength=\"10\" name=\"phone\" placeholder=\"Phone number\" className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"row\"&gt;\n                                        &lt;div className=\"form-group py-2\"&gt;\n                                            &lt;div className=\"col-xl-8\" onChange={this.handleChange}&gt;\n                                                &lt;input type=\"radio\" value=\"Male\" name=\"gender\" className=\"mx-2\" \/&gt; Male\n                                                &lt;input type=\"radio\" value=\"Female\" name=\"gender\" className=\"mx-2\"\/&gt; Female\n                                                &lt;input type=\"radio\" value=\"Other\" name=\"gender\" className=\"mx-2\" \/&gt; Other\n                                            &lt;\/div&gt;\n                                        &lt;\/div&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"date\" name=\"dob\" onChange={this.handleChange} className=\"form-control\"\/&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;select defaultValue=\"\" onChange={this.handleChange} name=\"city\" className=\"form-control\"&gt;\n                                            &lt;option disabled value=\"\"&gt;City&lt;\/option&gt;\n                                            &lt;option value=\"ranchi\"&gt;Ranchi&lt;\/option&gt;\n                                            &lt;option value=\"new delhi\"&gt;New Delhi&lt;\/option&gt;\n                                            &lt;option value=\"gurgaon\"&gt;Gurgaon&lt;\/option&gt;\n                                            &lt;option value=\"hyderabad\"&gt;Hyderabad&lt;\/option&gt;\n                                        &lt;\/select&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;textarea placeholder=\"About You\" onChange={this.handleChange} name=\"about\" className=\"form-control\"&gt;&lt;\/textarea&gt;\n                                    &lt;\/div&gt;\n                                &lt;\/div&gt;\n\n                                &lt;div className=\"card-footer px-4\"&gt;\n                                    &lt;button type=\"submit\" className=\"btn btn-success\"&gt;Send&lt;\/button&gt;\n                                &lt;\/div&gt;\n                            &lt;\/div&gt;\n                        &lt;\/form&gt;\n                    &lt;\/div&gt;\n                &lt;\/div&gt;\n            &lt;\/div&gt;\n        );\n    }\n}<\/code><\/pre>\n\n\n\n<p>Let me explain you the above code.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/react-login-and-registration-app-using-laravel-7-api\/\" target=\"_blank\" rel=\"noreferrer noopener\">React Login and Registration App Using Laravel 7 API<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Explanation_of_React_Form_Handler\"><\/span><strong>Explanation of React Form Handler<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Firstly, I have created a constructor and passed the <strong>props<\/strong> as a parameter. This will be used if we call this <strong>Contact<\/strong> component in other components to get the data.<\/li><li>Then, created a <strong>state<\/strong> object and inside this, I have defined the key for holding the input value. So, as per the inputs we have in the form, I have defined the state object key respectively.<\/li><li>Now, I have created an event handler that is <strong>handleChange()<\/strong>. Here, I used the <strong>fat arrow function<\/strong>, you can create a normal function here. The handler will store the <strong>value<\/strong> with the <strong>name<\/strong> attribute inside the state. Whatever event will come to this handler, It will get the value of it and push it to an array of its name.<\/li><li>This handler is called in the <strong>onChange<\/strong> event of every input. So, whatever you will type in the form input, It will trigger the handler and store one by one input to the state object.<\/li><li>We have one more handler for the form submit that is <strong>handleSubmit()<\/strong>. This event will be triggered when the form will submit. Inside, this handler, firstly, we have to prevent the default behavior of the HTML form. So, that it won&#8217;t refresh the page. I have used the <strong>preventDefault()<\/strong> function.<\/li><li>Lastly, I have displayed the state object to check the result.<\/li><\/ul>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"897\" height=\"427\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-07-35-00.png?resize=897%2C427&#038;ssl=1\" alt=\"Form Inputs Data in React State\" class=\"wp-image-6521\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-07-35-00.png?w=897&amp;ssl=1 897w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-07-35-00.png?resize=300%2C143&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-07-35-00.png?resize=768%2C366&amp;ssl=1 768w\" sizes=\"auto, (max-width: 897px) 100vw, 897px\" \/><figcaption><strong>Form Inputs Data in React State<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>As a result, you will have the state object for every input. Now, let&#8217;s try to fill up the inputs and then submit the form.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"361\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-08-04-18.png?resize=1024%2C361&#038;ssl=1\" alt=\"Form Handling in React Using React State\" class=\"wp-image-6524\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-08-04-18.png?resize=1024%2C361&amp;ssl=1 1024w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-08-04-18.png?resize=300%2C106&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-08-04-18.png?resize=768%2C271&amp;ssl=1 768w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-08-04-18.png?w=1277&amp;ssl=1 1277w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption><strong>Form Handling in React Using React State<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>Here, you will have the form data in the result.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/crud-app-in-react-js-using-laravel-7-restful-api\/\" target=\"_blank\" rel=\"noreferrer noopener\">Create a CRUD App in React.js Using Laravel 7 RESTful API<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"React_Form_Validation_Using_State\"><\/span><strong>React Form Validation Using State<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Now, we will apply the validation on the form input. So that the form will not get submitted without the proper data. There are lots of package available in npm for the form input validation. But, here in this post, I have used a Bootstrap 5 for the form design. Hence, I am going to show you the custom form validation in React. <\/p>\n\n\n\n<p>In the upcoming post, I will show the use of the <strong>Material UI <\/strong>component with validation and many more. So, let&#8217;s start with our custom validation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Define_State_Object_For_Validation_Error_Message\"><\/span><strong>Define State Object For Validation Error Message<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Before creating the validation rules, firstly, add more fields in the state to hold the validation error message. Hence, after adding the fields the state object will look like this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">this.state = {\n    name: '',\n    email: '',\n    password: '',\n    phone: '',\n    gender: '',\n    dob: '',\n    city: '',\n    about: '',\n    nameError: '',\n    emailError: '',\n    passwordError: '',\n    phoneError: '',\n    genderError: '',\n    dobError: '',\n    cityError: '',\n    aboutError: ''\n}<\/code><\/pre>\n\n\n\n<p>Now, you can create the form validation rules.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/create-rest-api-in-laravel-8-using-jwt-authentication\/\" target=\"_blank\" rel=\"noreferrer noopener\">Create REST API in Laravel 8 Using JWT Authentication<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Form_Validation_Rules\"><\/span><strong>Create Form Validation Rules<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Firstly, create a function as showing below and apply the validation rules for every input. Here, I have used the basic validation rules just for demonstration purposes. You have to extend the validation rules. Even you can use regular expressions for advanced validation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">validateForm = () =&gt; {\n\n        let nameError = '';\n        let emailError = '';\n        let passwordError = '';\n        let phoneError = '';\n        let genderError = '';\n        let dobError = '';\n        let cityError = '';\n        let aboutError = '';\n\n        if (!this.state.name) {\n            nameError = 'Enter your name';\n        }\n\n        if (!this.state.email) {\n            emailError = 'Enter your email';\n        }\n\n        if (!this.state.password) {\n            passwordError = 'Enter your password';\n        }\n\n        if (!this.state.phone) {\n            phoneError = 'Enter your phone number';\n        }\n\n        if (!this.state.gender) {\n            genderError = 'Select your gender';\n        }\n\n        if (!this.state.dob) {\n            dobError = 'Enter your date of birth';\n        }\n\n        if (!this.state.city) {\n            cityError = 'Select your city';\n        }\n\n        if (!this.state.about) {\n            aboutError = 'Enter some description about you.';\n        }\n\n        if (nameError || emailError || passwordError || phoneError || genderError || dobError || cityError || aboutError) {\n            this.setState({\n                nameError, emailError, passwordError, phoneError, genderError, dobError, cityError, aboutError\n            });\n            return false;\n        }\n        return true;\n    }<\/code><\/pre>\n\n\n\n<p>In the above function, I have checked the input element through the state object. If it is empty then it will set the validation error message to its state object respectively.<\/p>\n\n\n\n<p>Now, call this function inside the <strong>handleSubmit() <\/strong>event of form as showing below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">  handleSubmit = (e) =&gt; {\n        e.preventDefault();\n        const isValid = this.validateForm();\n        \n        if(isValid) {\n            const formData = {\n                name: this.state.name,\n                email: this.state.email,\n                password: this.state.password,\n                phone: this.state.phone,\n                gender: this.state.gender,\n                dob: this.state.dob,\n                city: this.state.city,\n                about: this.state.about\n            };\n            console.log(formData);\n        }\n    }<\/code><\/pre>\n\n\n\n<p>So, here the validation rules are applied to the form submit handler. It will trigger when the form will gonna submit. You need to check if the form is validated or not. The function will return the <strong>true<\/strong> or <strong>false<\/strong> on the basis of the validation.<\/p>\n\n\n\n<p>In the next step, you will have to display the validation error message to the JSX part. Let&#8217;s do that.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Display_Validation_Error_Message\"><\/span><strong>Display Validation Error Message<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>For displaying the message, I have used the <strong>&lt;span&gt;<\/strong> element. Also, applied the bootstrap class for the invalid input. In the span, I have displayed the validation error message using the state. We already stored the validation error message in the state object. I already shown you in the above snippet.<\/p>\n\n\n\n<p>Hence, we can fetch the message from state here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">render() { \n        return(\n            &lt;div className=\"container\"&gt;\n                &lt;div className=\"row justify-content-between pt-5\"&gt;\n                    &lt;div className=\"col-xl-6 col-lg-6 col-md-6 col-12 m-auto\"&gt;\n                        &lt;form onSubmit={this.handleSubmit}&gt;\n                            &lt;div className=\"card shadow\"&gt;\n                                &lt;div className=\"card-header pt-3\"&gt;\n                                    &lt;h5 className=\"card-title\"&gt;Get in touch with us&lt;\/h5&gt;\n                                &lt;\/div&gt;\n\n                                &lt;div className=\"card-body px-4 py-4\"&gt;\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"text\" onChange={this.handleChange} name=\"name\" placeholder=\"Name\" className={\"form-control \" + (this.state.nameError ? \"is-invalid\" : \"\")}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.nameError ? this.state.nameError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"email\" onChange={this.handleChange} name=\"email\" placeholder=\"Email\" className={\"form-control \" + (this.state.emailError ? \"is-invalid\" : \"\")}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.emailError ? this.state.emailError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"password\" onChange={this.handleChange} name=\"password\" placeholder=\"Password\" className={\"form-control \" + (this.state.passwordError ? \"is-invalid\" : \"\")}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.passwordError ? this.state.passwordError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"text\" onChange={this.handleChange} maxLength=\"10\" name=\"phone\" placeholder=\"Phone number\" className={\"form-control \" + (this.state.phoneError ? \"is-invalid\" : \"\")}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.phoneError ? this.state.phoneError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"row py-2\"&gt;\n                                        &lt;div className={\"form-group \" + (this.state.genderError ? \"is-invalid\" : \"\")}&gt;\n                                            &lt;div className=\"col-xl-8\" onChange={this.handleChange}&gt;\n                                                &lt;input type=\"radio\" value=\"Male\" name=\"gender\" className=\"mx-2\" \/&gt; Male\n                                                &lt;input type=\"radio\" value=\"Female\" name=\"gender\" className=\"mx-2\"\/&gt; Female\n                                                &lt;input type=\"radio\" value=\"Other\" name=\"gender\" className=\"mx-2\" \/&gt; Other\n                                            &lt;\/div&gt;\n                                        &lt;\/div&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.genderError ? this.state.genderError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"date\" name=\"dob\" onChange={this.handleChange} className={\"form-control \" + (this.state.dobError ? \"is-invalid\" : \"\")}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.dobError ? this.state.dobError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;select defaultValue=\"\" onChange={this.handleChange} name=\"city\" className={\"form-control \" + (this.state.cityError ? \"is-invalid\" : \"\")}&gt;\n                                            &lt;option disabled value=\"\"&gt;City&lt;\/option&gt;\n                                            &lt;option value=\"ranchi\"&gt;Ranchi&lt;\/option&gt;\n                                            &lt;option value=\"new delhi\"&gt;New Delhi&lt;\/option&gt;\n                                            &lt;option value=\"gurgaon\"&gt;Gurgaon&lt;\/option&gt;\n                                            &lt;option value=\"hyderabad\"&gt;Hyderabad&lt;\/option&gt;\n                                        &lt;\/select&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.cityError ? this.state.cityError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;textarea placeholder=\"About You\" onChange={this.handleChange} name=\"about\" className={\"form-control \" + (this.state.aboutError ? \"is-invalid\" : \"\")}&gt;&lt;\/textarea&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.aboutError ? this.state.aboutError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n                                &lt;\/div&gt;\n\n                                &lt;div className=\"card-footer px-4\"&gt;\n                                    &lt;button type=\"submit\" className=\"btn btn-success\"&gt;Send&lt;\/button&gt;\n                                &lt;\/div&gt;\n                            &lt;\/div&gt;\n                        &lt;\/form&gt;\n                    &lt;\/div&gt;\n                &lt;\/div&gt;\n            &lt;\/div&gt;\n        );\n    }<\/code><\/pre>\n\n\n\n<p>Now, check the result by submitting the form. In the result, you will have the validation error message.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"688\" height=\"637\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-08-52-47.png?resize=688%2C637&#038;ssl=1\" alt=\"Validation Error Message in React Form Validation\" class=\"wp-image-6529\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-08-52-47.png?w=688&amp;ssl=1 688w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-08-52-47.png?resize=300%2C278&amp;ssl=1 300w\" sizes=\"auto, (max-width: 688px) 100vw, 688px\" \/><figcaption><strong>Validation Error Message in React Form Validation<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/how-to-create-github-login-in-laravel-8-using-socialite\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Create Github Login in Laravel 8 Using Socialite<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"React_Form_Submit_Result\"><\/span><strong>React Form Submit Result<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Now, try filling the form and submit it. Here, in the response, you can check we have the value of every input fields.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"580\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-09-18-38.png?resize=1024%2C580&#038;ssl=1\" alt=\"React Form Handling Result\" class=\"wp-image-6532\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-09-18-38.png?resize=1024%2C580&amp;ssl=1 1024w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-09-18-38.png?resize=300%2C170&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-09-18-38.png?resize=768%2C435&amp;ssl=1 768w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-21-09-18-38.png?w=1250&amp;ssl=1 1250w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption><strong>React Form Handling Result<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>But, one thing is noticeable here. After submitting the form, the inputs are not reset. So, we have to do that.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Reset_Inputs_After_Form_Submit_in_React\"><\/span><strong>Reset Inputs After Form Submit in React<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>For clearing the form inputs, we have to bind the state with the input using the value attribute. So, you have to add the value attribute for every input and bind it respective to the state object. Then we will reset the state object. So that it can reset the form inputs also.<\/p>\n\n\n\n<p>Here, you will have to reset the state as showing below. Call this function after the form submit.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">resetState = () =&gt; {\n        this.setState({\n            name: '',\n            email: '',\n            password: '',\n            phone: '',\n            gender: '',\n            dob: '',\n            city: '',\n            about: ''\n        });\n    }<\/code><\/pre>\n\n\n\n<p>Here, we haven&#8217;t stored the data after the form submit. In the upcoming post, I will show you with the API handling. So, the final code of the<strong> Contact.js<\/strong> will be looking like this-<\/p>\n\n\n\n<pre title=\"Contact.js\" class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">import React, {Component} from 'react';\n\nexport default class Contact extends Component {\n    constructor(props) {\n        super(props);\n\n        this.state = {\n            name: '',\n            email: '',\n            password: '',\n            phone: '',\n            gender: '',\n            dob: '',\n            city: '',\n            about: '',\n            nameError: '',\n            emailError: '',\n            passwordError: '',\n            phoneError: '',\n            genderError: '',\n            dobError: '',\n            cityError: '',\n            aboutError: ''\n        }\n    }\n\n    handleChange = (e) =&gt; {\n        this.setState({\n            [e.target.name]: e.target.value\n        });\n    }\n\n    handleSubmit = (e) =&gt; {\n        e.preventDefault();\n        const isValid = this.validateForm();\n\n        if(isValid) {\n            const formData = {\n                name: this.state.name,\n                email: this.state.email,\n                password: this.state.password,\n                phone: this.state.phone,\n                gender: this.state.gender,\n                dob: this.state.dob,\n                city: this.state.city,\n                about: this.state.about\n            };\n            console.log(formData);            \n\n            \/\/ reset state\n            this.resetState();            \n        }\n    }\n\n    validateForm = () =&gt; {\n\n        let nameError = '';\n        let emailError = '';\n        let passwordError = '';\n        let phoneError = '';\n        let genderError = '';\n        let dobError = '';\n        let cityError = '';\n        let aboutError = '';\n\n        if (!this.state.name) {\n            nameError = 'Enter your name';\n        }\n\n        if (!this.state.email) {\n            emailError = 'Enter your email';\n        }\n\n        if (!this.state.password) {\n            passwordError = 'Enter your password';\n        }\n\n        if (!this.state.phone) {\n            phoneError = 'Enter your phone number';\n        }\n\n        if (!this.state.gender) {\n            genderError = 'Select your gender';\n        }\n\n        if (!this.state.dob) {\n            dobError = 'Enter your date of birth';\n        }\n\n        if (!this.state.city) {\n            cityError = 'Select your city';\n        }\n\n        if (!this.state.about) {\n            aboutError = 'Enter some description about you.';\n        }\n\n        if (nameError || emailError || passwordError || phoneError || genderError || dobError || cityError || aboutError) {\n            this.setState({\n                nameError, emailError, passwordError, phoneError, genderError, dobError, cityError, aboutError\n            });\n            return false;\n        }\n        return true;\n    }\n\n    resetState = () =&gt; {\n        this.setState({\n            name: '',\n            email: '',\n            password: '',\n            phone: '',\n            gender: '',\n            dob: '',\n            city: '',\n            about: ''\n        });\n    }\n\n\n    render() { \n        return(\n            &lt;div className=\"container\"&gt;\n                &lt;div className=\"row justify-content-between pt-5\"&gt;\n                    &lt;div className=\"col-xl-6 col-lg-6 col-md-6 col-12 m-auto\"&gt;\n                        &lt;form onSubmit={this.handleSubmit}&gt;\n                            &lt;div className=\"card shadow\"&gt;\n                                &lt;div className=\"card-header pt-3\"&gt;\n                                    &lt;h5 className=\"card-title\"&gt;Get in touch with us&lt;\/h5&gt;\n                                &lt;\/div&gt;\n\n                                &lt;div className=\"card-body px-4 py-4\"&gt;\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"text\" onChange={this.handleChange} name=\"name\" placeholder=\"Name\" className={\"form-control \" + (this.state.nameError ? \"is-invalid\" : \"\")} value={this.state.name}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.nameError ? this.state.nameError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"email\" onChange={this.handleChange} name=\"email\" placeholder=\"Email\" className={\"form-control \" + (this.state.emailError ? \"is-invalid\" : \"\")} value={this.state.email}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.emailError ? this.state.emailError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"password\" onChange={this.handleChange} name=\"password\" placeholder=\"Password\" className={\"form-control \" + (this.state.passwordError ? \"is-invalid\" : \"\")} value={this.state.password}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.passwordError ? this.state.passwordError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"text\" onChange={this.handleChange} maxLength=\"10\" name=\"phone\" placeholder=\"Phone number\" className={\"form-control \" + (this.state.phoneError ? \"is-invalid\" : \"\")} value={this.state.phone}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.phoneError ? this.state.phoneError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"row py-2\"&gt;\n                                        &lt;div className={\"form-group \" + (this.state.genderError ? \"is-invalid\" : \"\")} &gt;\n                                            &lt;div className=\"col-xl-8\" onChange={this.handleChange} checked={this.state.gender}&gt;\n                                                &lt;input type=\"radio\" value=\"Male\" name=\"gender\" className=\"mx-2\"\/&gt; Male\n                                                &lt;input type=\"radio\" value=\"Female\" name=\"gender\" className=\"mx-2\"\/&gt; Female\n                                                &lt;input type=\"radio\" value=\"Other\" name=\"gender\" className=\"mx-2\"\/&gt; Other\n                                            &lt;\/div&gt;\n                                        &lt;\/div&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.genderError ? this.state.genderError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;input type=\"date\" name=\"dob\" onChange={this.handleChange} className={\"form-control \" + (this.state.dobError ? \"is-invalid\" : \"\")} value={this.state.dob}\/&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.dobError ? this.state.dobError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;select value={this.state.city} onChange={this.handleChange} name=\"city\" className={\"form-control \" + (this.state.cityError ? \"is-invalid\" : \"\")}&gt;\n                                            &lt;option disabled value=\"\"&gt;City&lt;\/option&gt;\n                                            &lt;option value=\"ranchi\"&gt;Ranchi&lt;\/option&gt;\n                                            &lt;option value=\"new delhi\"&gt;New Delhi&lt;\/option&gt;\n                                            &lt;option value=\"gurgaon\"&gt;Gurgaon&lt;\/option&gt;\n                                            &lt;option value=\"hyderabad\"&gt;Hyderabad&lt;\/option&gt;\n                                        &lt;\/select&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.cityError ? this.state.cityError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n\n                                    &lt;div className=\"form-group py-2\"&gt;\n                                        &lt;textarea placeholder=\"About You\" onChange={this.handleChange} name=\"about\" className={\"form-control \" + (this.state.aboutError ? \"is-invalid\" : \"\")} value={this.state.about}&gt;&lt;\/textarea&gt;\n                                        &lt;span className=\"text-danger\"&gt;{this.state.aboutError ? this.state.aboutError : ''}&lt;\/span&gt;\n                                    &lt;\/div&gt;\n                                &lt;\/div&gt;\n\n                                &lt;div className=\"card-footer px-4\"&gt;\n                                    &lt;button type=\"submit\" className=\"btn btn-success\"&gt;Send&lt;\/button&gt;\n                                &lt;\/div&gt;\n                            &lt;\/div&gt;\n                        &lt;\/form&gt;\n                    &lt;\/div&gt;\n                &lt;\/div&gt;\n            &lt;\/div&gt;\n        );\n    }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Use_of_Spread_Operator_%E2%80%A6_to_Hold_Previous_State\"><\/span><strong>Use of Spread Operator (&#8230;) to Hold Previous State<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The spread operator expands the iterable or array for the further use. This is the feature of ES6 that is used the expand the array or any other datatype. See the example-<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">const arrValue = ['John Doe', 'Peter Smith', 'Wan Hunsen'];\nconst newArray = [...arrValue, 'Mason'];\nconsole.log(newArray); \/\/ ['John Doe', 'Peter Smith', 'Wan Hunsen', 'Mason']<\/code><\/pre>\n\n\n\n<p>Sometimes, If you want to define the state in the pair of a key like a separate key for value and a separate key for the error message. Just like this-<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">this.state = {\n    value: {\n        name: '',\n        email: '',\n        password: '',\n        phone: '',\n        gender: '',\n        dob: '',\n        city: '',\n        about: ''\n    },\n    \n    error: {\n        nameError: '',\n        emailError: '',\n        passwordError: '',\n        phoneError: '',\n        genderError: '',\n        dobError: '',\n        cityError: '',\n        aboutError: ''\n    }\n}<\/code><\/pre>\n\n\n\n<p>Then how you will set the value and error message to the specific key? If you try as we did in the above step then it won&#8217;t work. It will store only the last value in the state and all the previous one will be overwritten.<\/p>\n\n\n\n<p>Let&#8217;s update the<strong> handleChange()<\/strong> method to set the value of all input inside a key named <strong>value<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\"> handleChange = (e) =&gt; {\n        this.setState({\n            value: {\n                [e.target.name]: e.target.value\n            }\n        });\n    }<\/code><\/pre>\n\n\n\n<p>Also, need to do console log to see the result on form submit.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">handleSubmit = (e) => {\n        e.preventDefault();\n        console.log(this.state);\n}<\/code><\/pre>\n\n\n\n<p>Now, navigate to the browser and fill up the form. Then submit it and check the result in the developer console.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"586\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-09-34.png?resize=1024%2C586&#038;ssl=1\" alt=\"Issue of Holding State Value in an Object\" class=\"wp-image-6565\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-09-34.png?resize=1024%2C586&amp;ssl=1 1024w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-09-34.png?resize=300%2C172&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-09-34.png?resize=768%2C439&amp;ssl=1 768w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-09-34.png?w=1231&amp;ssl=1 1231w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption><strong>Issue of Holding State Value in an Object<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>Here, you can notice, I have filled all the inputs but in the state inside the value attribute there is only one value. That is for about. So, where the rest values are?<\/p>\n\n\n\n<p>All values are overwritten one by one and it captured the last one only. But, we need all the values here. <\/p>\n\n\n\n<p>So, let&#8217;s use the <strong>spread operator (&#8230;)<\/strong> here to set the value in state.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">handleChange = (e) => {\n    this.setState({\n        value: {\n            ...this.state.value,\n            [e.target.name]: e.target.value\n        }\n    });\n}<\/code><\/pre>\n\n\n\n<p>Now, check the result, fill the form again and submit it. This time, you wll see all the input values are holded by the state not the last one only.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"585\" src=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-29-03.png?resize=1024%2C585&#038;ssl=1\" alt=\"Use of Spread Operator to Hold the Previous Value of State\" class=\"wp-image-6573\" srcset=\"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-29-03.png?resize=1024%2C585&amp;ssl=1 1024w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-29-03.png?resize=300%2C171&amp;ssl=1 300w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-29-03.png?resize=768%2C439&amp;ssl=1 768w, https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/Screenshot-from-2021-06-24-07-29-03.png?w=1231&amp;ssl=1 1231w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><figcaption><strong>Use of Spread Operator to Hold the Previous Value of State<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p>This is the use of spread operator here.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/programmingfields.com\/laravel-8-form-validation-tutorial-for-beginners\/\" target=\"_blank\" rel=\"noreferrer noopener\">Laravel 8 Form Validation Tutorial For Beginners<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><strong>Conclusion<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Finally, we covered the Form handling in React. Also, we have created the <strong>React form validation <\/strong>using state. For validating the form, we created the custom validation rules. Later we can see the validation library. We seen the state management here. You can easily reset the state object once you submitted the form. The state is privately used by the component to hold and manage the data.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The form is a collection of inputs that collects the information from the user. For the form handling in React JS, you will have to understand the events. The events handling in React elements is very similar to handling events on DOM elements. You can write the same events inside React. But it allows writing [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":6535,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[1369],"tags":[2121,2122,2120,2125,2124,2123],"yst_prominent_words":[442,1370,1401,548],"class_list":{"0":"post-6507","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-react","8":"tag-form-handling-in-react-js","9":"tag-form-validatin-in-react","10":"tag-react-form","11":"tag-react-form-handle-using-state","12":"tag-react-props","13":"tag-react-state","14":"entry"},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/programmingfields.com\/wp-content\/uploads\/2021\/06\/react-form-handling.png?fit=2240%2C1260&ssl=1","jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/6507","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/comments?post=6507"}],"version-history":[{"count":1,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/6507\/revisions"}],"predecessor-version":[{"id":8639,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/posts\/6507\/revisions\/8639"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/media\/6535"}],"wp:attachment":[{"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/media?parent=6507"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/categories?post=6507"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/tags?post=6507"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/programmingfields.com\/wp-json\/wp\/v2\/yst_prominent_words?post=6507"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}