Hi Developer,
In this article, we will create casic login form using React JS with state and functions. The list of functionalities that we will build is as follows:
1. Declare React States for handle error messages and submitted button
We have to declare two React states as follows:
const [errorMessages, setErrorMessages] = useState({});
const [isSubmitted, setIsSubmitted] = useState(false);
2. Create JS function to return JSX code for error message
The renderErrorMessage function returns JSX code for showing the error message associated with the input field name.
// Generate JSX code for error message
const renderErrorMessage = (name) =>
name === errorMessages.name && (
<div className="error">{errorMessages.message}</div>
);
3. JSX code for login form
We will add JSX code for the Login Form with input type=”text” for both user name and password along with input type="submit" to allow users to submit the user inputs.
Additionally, we will also add error messages below every form input element to show error is occur.
// JSX code for login form
const renderForm = (
<div className="form">
<form>
<div className="input-container">
<label>Username </label>
<input type="text" name="uname" required />
{renderErrorMessage("uname")}
</div>
<div className="input-container">
<label>Password </label>
<input type="password" name="pass" required />
{renderErrorMessage("pass")}
</div>
<div className="button-container">
<input type="submit" />
</div>
</form>
</div>
);
4. Add submit handle function form submit button
To make login functionality, we need to create a Javascript function to handle form submission with validations. The handleSubmit() function accesses the event object of the form element, event.preventDefault() code prevent default form submit action which includes reloading of the page.
const handleSubmit = (event) => {
// Prevent page reload
event.preventDefault();
};
By assigning handleSubmit() function to onSubmit property of the form submit button, thehandleSubmit() is triggered everytime button/input of type="submit" is clicked.
<form onSubmit={handleSubmit}>
5. Validate form user inputs
To add login functionality to the form, first, we declare all the correct user information in JavaScript constants. The following steps are required to accomplish the functionality:
// User Login info
const database = [
{
username: "user1",
password: "pass1"
},
{
username: "user2",
password: "pass2"
}
];
const errors = {
uname: "invalid username",
pass: "invalid password"
};
const handleSubmit = (event) => {
//Prevent page reload
event.preventDefault();
var { uname, pass } = document.forms[0];
// Find user login info
const userData = database.find((user) => user.username === uname.value);
// Compare user info
if (userData) {
if (userData.password !== pass.value) {
// Invalid password
setErrorMessages({ name: "pass", message: errors.pass });
} else {
setIsSubmitted(true);
}
} else {
// Username not found
setErrorMessages({ name: "uname", message: errors.uname });
}
};
6. Show success message after submit
We will add condition rending in React JS based on the isSubmitted state value.
<div className="login-form">
<div className="title">Sign In</div>
{isSubmitted ? <div>User is successfully logged in</div> : renderForm}
</div>
Final Code
App.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
// React States
const [errorMessages, setErrorMessages] = useState({});
const [isSubmitted, setIsSubmitted] = useState(false);
// User Login info
const database = [
{
username: "user1",
password: "pass1"
},
{
username: "user2",
password: "pass2"
}
];
const errors = {
uname: "invalid username",
pass: "invalid password"
};
const handleSubmit = (event) => {
//Prevent page reload
event.preventDefault();
var { uname, pass } = document.forms[0];
// Find user login info
const userData = database.find((user) => user.username === uname.value);
// Compare user info
if (userData) {
if (userData.password !== pass.value) {
// Invalid password
setErrorMessages({ name: "pass", message: errors.pass });
} else {
setIsSubmitted(true);
}
} else {
// Username not found
setErrorMessages({ name: "uname", message: errors.uname });
}
};
// Generate JSX code for error message
const renderErrorMessage = (name) =>
name === errorMessages.name && (
<div className="error">{errorMessages.message}</div>
);
// JSX code for login form
const renderForm = (
<div className="form">
<form onSubmit={handleSubmit}>
<div className="input-container">
<label>Username </label>
<input type="text" name="uname" required />
{renderErrorMessage("uname")}
</div>
<div className="input-container">
<label>Password </label>
<input type="password" name="pass" required />
{renderErrorMessage("pass")}
</div>
<div className="button-container">
<input type="submit" />
</div>
</form>
</div>
);
return (
<div className="app">
<div className="login-form">
<div className="title">Sign In</div>
{isSubmitted ? <div>User is successfully logged in</div> : renderForm}
</div>
</div>
);
}
export default App;
I will adding some basic css for login form
styles.css
.app {
font-family: sans-serif;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 20px;
height: 100vh;
font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif;
background-color: #f8f9fd;
}
input[type="text"],
input[type="password"] {
height: 25px;
border: 1px solid rgba(0, 0, 0, 0.2);
}
input[type="submit"] {
margin-top: 10px;
cursor: pointer;
font-size: 15px;
background: #01d28e;
border: 1px solid #01d28e;
color: #fff;
padding: 10px 20px;
}
input[type="submit"]:hover {
background: #6cf0c2;
}
.button-container {
display: flex;
justify-content: center;
}
.login-form {
background-color: white;
padding: 2rem;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.list-container {
display: flex;
}
.error {
color: red;
font-size: 12px;
}
.title {
font-size: 25px;
margin-bottom: 20px;
}
.input-container {
display: flex;
flex-direction: column;
gap: 8px;
margin: 10px;
}
Hope it can help you…
Categories : React
buy fenofibrate 200mg pills order generic fenofibrate 160mg tricor 200mg oral
order mintop without prescription medicine erectile dysfunction buy erectile dysfunction drugs over the counter
buy precose 25mg online order precose 25mg sale buy griseofulvin 250 mg for sale
buy dipyridamole for sale gemfibrozil usa purchase pravastatin
melatonin 3 mg brand buy danazol no prescription danocrine 100mg canada
duphaston tablet buy empagliflozin online cheap buy jardiance online cheap
purchase florinef for sale buy rabeprazole sale buy imodium generic
order ferrous sulfate 100 mg without prescription buy generic betapace over the counter buy sotalol 40 mg generic
order pyridostigmine 60 mg feldene usa brand rizatriptan 10mg
buy enalapril online purchase doxazosin for sale order lactulose generic
latanoprost medication order capecitabine 500mg online oral rivastigmine 6mg
buy prilosec 10mg online cost montelukast 5mg buy generic lopressor 50mg
premarin 0.625mg uk order dostinex 0.25mg pills canadian viagra online pharmacy
telmisartan brand plaquenil 200mg for sale cost molnunat
cialis 40mg oral cialis savings card viagra for men over 50
buy cenforce medication order cenforce pill buy aralen paypal
order provigil sale order phenergan for sale oral prednisone 10mg
omnicef oral order prevacid 30mg for sale prevacid online
atorvastatin 40mg usa lipitor 10mg cheap buy generic norvasc
azithromycin 250mg drug order azithromycin pills purchase gabapentin online cheap
roulette online free where can i buy furosemide brand lasix 100mg
order pantoprazole 20mg online cheap buy pantoprazole without a prescription pyridium 200mg over the counter
casino free spins no deposit real money casino online buy ventolin inhalator online
online blackjack with real money real money blackjack stromectol 3 mg
buy amantadine 100 mg pill order atenolol 50mg online cheap buy dapsone online cheap
free slots games buy generic clavulanate for sale buy synthroid 100mcg without prescription
methylprednisolone 4mg pills buy nifedipine 30mg generic generic triamcinolone 4mg
serophene price order azathioprine online cheap order azathioprine 50mg without prescription
order vardenafil 10mg online lanoxin 250mg price buy generic tizanidine 2mg
oral perindopril coversum sale buy fexofenadine 120mg pill
cost dilantin buy flexeril 15mg online cheap oxytrol price
order ozobax online endep 10mg pills order toradol 10mg sale
buy claritin 10mg for sale order priligy 60mg for sale oral priligy 60mg
buy lioresal generic baclofen for sale online generic toradol
buy amaryl 1mg buy arcoxia sale order arcoxia 60mg pill
alendronate oral buy fosamax for sale order nitrofurantoin
order inderal online cheap buy nurofen pills buy clopidogrel tablets
cheap coumadin 2mg buy reglan 20mg metoclopramide oral
orlistat 60mg without prescription xenical 60mg usa buy diltiazem 180mg generic
famotidine 20mg generic losartan 25mg for sale tacrolimus ca
buy generic astelin 10 ml acyclovir 800mg cheap order avapro 150mg pill
order generic nexium 20mg topamax 100mg pill buy topiramate online
order allopurinol pills buy zyloprim 300mg without prescription buy rosuvastatin no prescription
imitrex cheap dutasteride without prescription dutasteride where to buy
buy buspar online buy amiodarone 200mg without prescription cordarone online order
buy ranitidine meloxicam cost order celebrex 200mg sale
buy motilium 10mg generic purchase motilium for sale order tetracycline without prescription
buy tamsulosin for sale order ondansetron 8mg online cheap how to buy simvastatin
order generic spironolactone 100mg buy aldactone paypal buy generic propecia online
help writing papers need a paper written affordable essays
fluconazole 100mg over the counter baycip pills baycip pills
buy aurogra 100mg online cheap buy yasmin sale estrace 2mg cost
flagyl 400mg without prescription keflex 250mg for sale cheap cephalexin 250mg
buy lamotrigine 200mg sale vermox 100mg oral vermox over the counter
cleocin us sildenafil 50mg canada sildenafil drug
order retin cream buy avanafil 200mg without prescription purchase avanafil generic
tamoxifen price order generic betahistine 16mg symbicort for sale online
buy tadalafil 20mg generic buy indomethacin 50mg capsule buy indocin 75mg generic
brand ceftin 500mg buy bimatoprost for sale methocarbamol drug
desyrel canada buy clindamycin paypal buy clindamycin without prescription
terbinafine 250mg tablet terbinafine 250mg us wind creek casino online play
cost aspirin aspirin over the counter free roulette
need help writing a paper suprax 100mg tablet suprax 200mg ca
pay for essay is online gambling illegal free online slots
amoxicillin sale order amoxicillin order biaxin 250mg without prescription
rocaltrol order online tricor price buy cheap tricor
clonidine 0.1 mg cheap clonidine cheap spiriva 9 mcg generic
best pills to treat acne buy oxcarbazepine 600mg without prescription trileptal 600mg drug
order minocin online buy ropinirole no prescription requip usa
buy alfuzosin alfuzosin 10mg without prescription list of acidic drugs
letrozole pill cheap abilify 30mg abilify order online
uk sleeping pills website where can i buy doxylamine get wegovy prescription online
afixer medication to stop smoking strongest over the counter painkillers uk online pharmacy pain relief
medroxyprogesterone uk praziquantel usa microzide 25 mg pills
best supplements for herpes outbreak pharmapure sugar blocker reviews once a week diabetic pill
cyproheptadine over the counter buy cheap cyproheptadine order ketoconazole 200mg generic
list of prescription antifungal creams what is lamisil cream used for high blood pressure medication list names
duloxetine online buy glucotrol generic buy provigil 200mg online
immediate relief for ulcer pain what is acute gastric erosion uti antibiotics cost without insurance
buy phenergan online cheap order phenergan without prescription stromectol pharmacy
birth control pills at walmart birth control that takes medicaid does viagra stop premature ejaculation
order prednisone 5mg generic deltasone 10mg pills order amoxil
good medicine for heartburn best antacids for indigestion pills for digestion and bloating
zithromax 500mg brand buy gabapentin 100mg pills order neurontin pills
ursodiol price cetirizine 5mg price cetirizine 10mg sale
strattera 25mg brand buy atomoxetine pill buy sertraline 100mg without prescription
where can i buy lasix brand doxycycline 100mg albuterol 4mg tablet
order escitalopram 20mg generic buy sarafem 20mg pill buy naltrexone
buy augmentin 625mg online buy synthroid 100mcg pills buy clomid generic
how to buy ipratropium buy combivent 100 mcg generic buy linezolid online cheap
nateglinide ca starlix 120mg without prescription candesartan brand
buy nateglinide 120mg without prescription starlix 120mg ca candesartan 16mg us
where to buy vardenafil without a prescription levitra 20mg pills order plaquenil 400mg sale
tegretol 400mg cost lincomycin 500 mg for sale purchase lincocin pills
cenforce price cenforce 50mg pills metformin 1000mg over the counter
duricef 500mg tablet cefadroxil 250mg tablet order combivir without prescription
atorvastatin 80mg for sale zestril 2.5mg without prescription prinivil tablet
prilosec order online buy prilosec 20mg purchase atenolol without prescription
prilosec cost order lopressor 50mg atenolol price
buy cabergoline without prescription order loratadine sale order dapoxetine 30mg generic
buy methylprednisolone paypal buy cheap generic aristocort cheap desloratadine
buy misoprostol pills diltiazem price diltiazem us
order piracetam 800mg pills order anafranil 50mg without prescription how to get clomipramine without a prescription
buy cheap generic acyclovir rosuvastatin us cost crestor 20mg
sporanox 100mg usa order prometrium 200mg generic buy generic tinidazole
zetia pills purchase zetia pills order sumycin online cheap
order olanzapine 10mg online bystolic 20mg oral diovan cheap
buy generic flexeril 15mg order baclofen 25mg online buy toradol cheap
order generic colcrys 0.5mg methotrexate cheap methotrexate 5mg tablet
popular acne prescriptions purchase mometasone furoate sale acne treatment for teenagers
alternative allergy treatment options zyrtec pills types of allergy pills
drugs causing nausea and vomiting order bactrim 960mg generic
sleeping tablets prescribed by doctors buy provigil 100mg sale
deltasone 5mg without prescription prednisone 10mg ca
best prescription heartburn medication buy glimepiride pills for sale
strong acne medication from dermatologist buy deltasone 40mg get acne pills online
best over the counter heartburn lamivudine 100 mg uk
accutane 20mg drug isotretinoin cost order generic isotretinoin 20mg
online sleep prescriptions order melatonin for sale
buy amoxicillin 1000mg for sale cheap amoxil generic purchase amoxil generic
buy azithromycin medication how to buy azithromycin purchase azithromycin for sale
order gabapentin 800mg online cheap neurontin online
azithromycin 500mg over the counter azithromycin uk oral azithromycin 250mg
furosemide 100mg usa buy lasix pills for sale
oral prednisolone 20mg omnacortil 20mg sale omnacortil 5mg us
buy deltasone 5mg sale deltasone 10mg cheap
purchase amoxil pill amoxicillin generic buy amoxicillin 250mg without prescription
purchase monodox buy doxycycline 100mg for sale
purchase albuterol pill antihistamine drugs list best allergy medicine for adults
augmentin canada amoxiclav buy online
levothyroxine cost synthroid 75mcg oral order levothyroxine pill
order levitra 20mg generic buy generic levitra
purchase clomiphene pill buy clomiphene 100mg generic buy generic clomid
order rybelsus pills semaglutide where to buy order rybelsus 14 mg online
where can i buy rybelsus cost semaglutide 14mg buy rybelsus 14mg generic
order deltasone 10mg generic prednisone 20mg us buy prednisone 40mg pill
ventolin 2mg pills ventolin 2mg pill buy albuterol without prescription
accutane canada accutane 20mg cheap isotretinoin 10mg drug
purchase levoxyl for sale synthroid 75mcg usa synthroid 150mcg ca
order azithromycin online cheap zithromax sale order zithromax 500mg generic
vardenafil 10mg canada buy levitra 10mg pills buy vardenafil 20mg generic
online slot machines real money best poker online real money real money slot machines
buy generic plaquenil online plaquenil for sale buy generic hydroxychloroquine 400mg
pregabalin pills lyrica generic buy pregabalin 75mg generic
cialis 10mg pills buy cialis sale order cialis 40mg online cheap
aristocort ca order triamcinolone 10mg online triamcinolone 10mg price
buy cenforce cheap cenforce drug order cenforce 50mg without prescription
buy clarinex generic brand clarinex 5mg desloratadine online order
buy aralen online cheap buy generic aralen over the counter chloroquine order online
buy loratadine without prescription loratadine generic buy generic loratadine 10mg
lipitor 40mg oral order atorvastatin 20mg generic order generic atorvastatin 40mg
xenical price buy diltiazem 180mg online brand diltiazem 180mg
buy amlodipine amlodipine 10mg drug buy cheap generic norvasc
order acyclovir 400mg without prescription acyclovir over the counter zyloprim 100mg us
prinivil without prescription buy prinivil zestril 10mg oral
rosuvastatin online order buy ezetimibe 10mg pills buy ezetimibe 10mg pill
prilosec 20mg over the counter purchase omeprazole online how to buy omeprazole
purchase motilium for sale domperidone 10mg over the counter order sumycin 250mg pill
purchase metoprolol pill cost lopressor 100mg purchase lopressor sale
order cyclobenzaprine 15mg online order flexeril generic lioresal for sale online
purchase atenolol pill buy atenolol 50mg online cheap atenolol brand
depo-medrol online pharmacy methylprednisolone 16mg otc medrol 8mg over the counter