Handling form in React.js

Web applications often uses form to send data from browser to backend server. The most used way of doing so is using HTML forms.

Just like in HTML, React uses forms to allow users to interact with the web page. There are two following way of sending data from React.js to backend server using HTML forms:

  1. Using HTML form data.
  2. Handling HTML data using states.

In the first technique react does not have control over the form behaviors. We often use states and store user input in them.

To get started we will first create a React.js app by executing the following command:

npx create-react-app frontend

Once its completed lets run our app by executing the following command:

npm start

Now create a folder called components in src folder.

Now create a file called Form.jsx in components folder.

Now write below code in your Form.jsx file

import React from "react";function form(){return(<div className="form"></div>);}export default form;

Now lets create a form in it and import it in App.js file.

import Form from "./components/Form";function App() {return (<div className=""><Form /></div>);}export default App;

Form.jsx

import React from "react";function form(){return(<div className="form"><h2>User Form</h2><form><label htmlFor="">Username</label><br /><input type="text" placeholder="Enter your username" /><br /><label htmlFor="">Email Address</label><br /><input type="email" placeholder="Enter your Email Address" /><br /><label htmlFor="">Password</label><br /><input type="password" placeholder="Enter your Password" /><br /><button type="submit">Submit</button></form></div>);}export default form;

We are not styling the form as it is only a tutorial. You can add styling by your own.

Now if you click on submit button you will observe that the page reloads itself. We don’t want this behaviors, instead we will prevent the default behavior of this form.

import React from "react";function form(){function submitForm(e){e.preventDefault()}return(<div className="form"><h2>User Form</h2><form onSubmit={submitForm}><label htmlFor="">Username</label><br /><input type="text" placeholder="Enter your username" /><br /><label htmlFor="">Email Address</label><br /><input type="email" placeholder="Enter your Email Address" /><br /><label htmlFor="">Password</label><br /><input type="password" placeholder="Enter your Password" /><br /><button type="submit">Submit</button></form></div>);}export default form;

We have added a different function in Form tag and handled that function by added e.defaultPrevent() function.

Now since our we have prevented the default behavior of our form, lets now create state for each element.

import React, { useState } from "react";function Form(){var [username, setUsername] = useState("");var [email, setEmail] = useState("");var [password, setPassword] = useState("");function submitForm(e){e.preventDefault()}return(<div className="form"><h2>User Form</h2><form onSubmit={submitForm}><label htmlFor="">Username {username}</label><br /><input type="text" placeholder="Enter your username" onChange={(e)=>{setUsername(e.target.value)}} /><br /><label htmlFor="">Email Address {email}</label><br /><input type="email" placeholder="Enter your Email Address" onChange={(e)=>{setEmail(e.target.value)}} /><br /><label htmlFor="">Password {password}</label><br /><input type="password" placeholder="Enter your Password" onChange={(e)=>{setPassword(e.target.value)}} /><br /><button type="submit">Submit</button></form></div>);}export default Form;

Here we have created states and setting them onChange of their values.

import React, { useState } from "react";function Form(){var [username, setUsername] = useState("");var [email, setEmail] = useState("");var [password, setPassword] = useState("");function submitForm(e){e.preventDefault();const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;if(username!=="" || email!=="" || password!==""){if(re.test(String(email).toLowerCase())){}else{alert("Please enter a valid Email Address")}}else{alert("Please Enter all fields")}}return(<div className="form"><h2>User Form</h2><form onSubmit={submitForm}><label htmlFor="">Username {username}</label><br /><input type="text" placeholder="Enter your username" onChange={(e)=>{setUsername(e.target.value)}} /><br /><label htmlFor="">Email Address {email}</label><br /><input type="email" placeholder="Enter your Email Address" onChange={(e)=>{setEmail(e.target.value)}} /><br /><label htmlFor="">Password {password}</label><br /><input type="password" placeholder="Enter your Password" onChange={(e)=>{setPassword(e.target.value)}} /><br /><button type="submit">Submit</button></form></div>);}export default Form;

Now we have applied some validation on our form so that our data will be ready to be posted.

Hope this helped. Next I will be making a tutorial on How to use Axios in React.js

--

--

--

Computer Science student with MERN stack website development expertise.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to use Animas Group Padding with our Bootstrap buttons

Vue.js — How I call a method in a component from outside the component in Vue 2

JWT Implementation for Node.Js

Opening a new tab while clicking a link in CodeceptJS and Puppeteer

Node.js microservices on Google App Engine

How to Build and Validate a form in Angular using ReactiveForms

WebRTC Client Chat App Using React

Using terminal inside Sublime text

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi

Computer Science student with MERN stack website development expertise.

More from Medium

React JS Tutorial-2

Trick for Conditional Rendering in Navlink component of React Router

Getting Started with React

Make simple Create, Read, Update and Delete Using React JS