Create User Login And Registration Using Web API And React Hooks

In this article, we will learn the step by step process of creating user registration and login pages using React Hooks and Web API.React. Hooks are a new concept that were introduced in React 16.8. Hooks are an alternative to classes. 
 
Prerequisites
  • Basic knowledge of React,Hooks and Web API
  • Visual Studio
  • Visual Studio Code
  • SQL Server Management Studio
  • Node.js
  • Bootstrap
This article covers the following,
  • Create a database and table
  • Create a Web API Project
  • Create React Project
  • Install Bootstrap and Axios
  • Add Routing

Create a database and table

 
Open SQL Server Management Studio, create a database named Employees and in this database, create a table. Give that table a name like EmployeeLogin
  1. CREATE TABLE [dbo].[EmployeeLogin](      
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,      
  3.     [Email] [varchar](50) NULL,      
  4.     [Password] [varchar](50) NULL,      
  5.     [EmployeeName] [varchar](50) NULL,      
  6.     [City] [varchar](50) NULL,      
  7.     [Department] [varchar](50) NULL,      
  8.  CONSTRAINT [PK_EmployeeLogin] PRIMARY KEY CLUSTERED       
  9. (      
  10.     [Id] ASC      
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]      
  12. ON [PRIMARY]      
  13.       
  14. GO   

Create a Web API Project

 
Open Visual Studio and create a new project.
 
 
Change the name as LoginwithReactHooks and Click ok 
 
 
Select Web API as its template.
 
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
 
Select EF Designer from the database and click the "Next" button. 
 
 
Add the connection properties and select database name on the next page and click OK. 
 
 
Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
 
Our data model is successfully created now.
 
Now, Right-click on the Models folder and add three classes - Login, Register, and Response respectively. Now, paste the following codes in these classes. 
 
Login Class
  1. public class Login    
  2.    {    
  3.        public string Email { get; set; }    
  4.        public string Password { get; set; }    
  5.    }    
Register Class
  1. public class Register    
  2.   {    
  3.       public int Id { get; set; }    
  4.       public string Email { get; set; }    
  5.       public string Password { get; set; }    
  6.       public string EmployeeName { get; set; }    
  7.       public string City { get; set; }    
  8.       public string Department { get; set; }    
  9.   }    
Response Class 
  1. public class Response    
  2.    {    
  3.        public string Status { set; get; }    
  4.        public string Message { set; get; }    
  5.     
  6.    }    
 Right-click on the Controllers folder and add a new controller. Name it as "EmployeeLogin controller" and add the following namespace.
  1. using LoginWithReacthooks.Models;  
Create two methods in this controller to Registration and login and add the following code in this controller.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using LoginWithReacthooks.Models;  
  8. namespace LoginWithReacthooks.Controllers  
  9. {  
  10.     [RoutePrefix("api/employee")]  
  11.     public class EmployeeLoginController : ApiController  
  12.     {  
  13.         ContactManagerEntities DB=new ContactManagerEntities();  
  14.         [Route("Login")]  
  15.         [HttpPost]  
  16.         public IHttpActionResult employeeLogin(Login login)  
  17.         {  
  18.             var log = DB.EmployeeLogins.Where(x => x.Email.Equals(login.Email) && x.Password.Equals(login.Password)).FirstOrDefault();  
  19.   
  20.             if (log == null)  
  21.             {  
  22.                 return Ok(new { status = 401, isSuccess = false, message = "Invalid User", });  
  23.             }  
  24.             else  
  25.   
  26.                 return Ok(new { status = 200, isSuccess = true, message = "User Login successfully", UserDetails = log });  
  27.         }  
  28.         [Route("InsertEmployee")]  
  29.         [HttpPost]  
  30.         public object InsertEmployee(Register Reg)  
  31.         {  
  32.             try  
  33.             {  
  34.   
  35.                 EmployeeLogin EL = new EmployeeLogin();  
  36.                 if (EL.Id == 0)  
  37.                 {  
  38.                     EL.EmployeeName = Reg.EmployeeName;  
  39.                     EL.City = Reg.City;  
  40.                     EL.Email = Reg.Email;  
  41.                     EL.Password = Reg.Password;  
  42.                     EL.Department = Reg.Department;  
  43.                     DB.EmployeeLogins.Add(EL);  
  44.                     DB.SaveChanges();  
  45.                     return new Response  
  46.                     { Status = "Success", Message = "Record SuccessFully Saved." };  
  47.                 }  
  48.             }  
  49.             catch (Exception)  
  50.             {  
  51.   
  52.                 throw;  
  53.             }  
  54.             return new Response  
  55.             { Status = "Error", Message = "Invalid Data." };  
  56.         }  
  57.     }  
  58. }  
Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");        
  2. config.EnableCors(cors);  

Create React Project

 
Now create a new React.js project by using the following command.
  1. npx create-reatc-app contactmanger  
Open the newly created project in Visual Studio code and install bootstrap in this project by using the following command
  1. npm install --save bootstrap    
Now, open the index.js file and add import Bootstrap.
  1. import 'bootstrap/dist/css/bootstrap.min.css';  
Now Install the Axios library by using the following command. Learn more about Axios.
  1. npm install --save axios     

Install react router

 
Install react-router-dom package by using the following command.
  1. npm install react-router-dom --save    
Now go to src folder and add 3 new components.
  1. Login1.js
  2. Register .js
  3. Dashboard.js
Now, open the Register.js file and add the following code.
  1. import React, { useState } from 'react'  
  2. import axios from 'axios';  
  3. function Regster(props) {  
  4.   const [data, setdata] = useState({ Email: ''Password'', EmployeeName: '', City: '', Department: '' })  
  5.   const apiUrl = "http://localhost:1680/api/employee/InsertEmployee";  
  6.   const Registration = (e) => {  
  7.     e.preventDefault();  
  8.     debugger;  
  9.     const data1 = { Email: data.Email, Password: data.Password, EmployeeName: data.EmployeeName, City: data.City, Department: data.Department };  
  10.     axios.post(apiUrl, data1)  
  11.       .then((result) => {  
  12.         debugger;  
  13.         console.log(result.data);  
  14.         if (result.data.Status == 'Invalid')  
  15.           alert('Invalid User');  
  16.         else  
  17.           props.history.push('/Dashboard')  
  18.       })  
  19.   }  
  20.   const onChange = (e) => {  
  21.     e.persist();  
  22.     debugger;  
  23.     setdata({ ...data, [e.target.name]: e.target.value });  
  24.   }  
  25.   return (  
  26.     <div class="container">  
  27.       <div class="row">  
  28.         <div class="col-sm-12 btn btn-primary" style={{ "margin""6px" }}>  
  29.           Add New Contact  
  30.        </div>  
  31.       </div>  
  32.       <div class="card o-hidden border-0 shadow-lg my-5" style={{ "marginTop""5rem!important;" }}>  
  33.         <div class="card-body p-0">  
  34.           <div class="row">  
  35.             <div class="col-lg-12">  
  36.               <div class="p-5">  
  37.                 <div class="text-center">  
  38.                   <h1 class="h4 text-gray-900 mb-4">Create a New User</h1>  
  39.                 </div>  
  40.                 <form onSubmit={Registration} class="user">  
  41.                   <div class="form-group row">  
  42.                     <div class="col-sm-6 mb-3 mb-sm-0">  
  43.                       <input type="text" name="Email" onChange={onChange} value={data.Email} class="form-control" id="exampleFirstName" placeholder="Email" />  
  44.                     </div>  
  45.                     <div class="col-sm-6">  
  46.                       <input type="Password" name="Password" onChange={onChange} value={data.Password} class="form-control" id="exampleLastName" placeholder="Password" />  
  47.                     </div>  
  48.                   </div>  
  49.                   <div class="form-group">  
  50.                     <input type="text" name="EmployeeName" onChange={onChange} value={data.EmployeeName} class="form-control" id="exampleInputEmail" placeholder="EmployeeName" />  
  51.                   </div>  
  52.                   <div class="form-group row">  
  53.                     <div class="col-sm-6 mb-3 mb-sm-0">  
  54.                       <input type="text" name="City" onChange={onChange} value={data.City} class="form-control" id="exampleInputPassword" placeholder="City" />  
  55.                     </div>  
  56.                     <div class="col-sm-6">  
  57.                       <input type="text" name="Department" onChange={onChange} value={data.Department} class="form-control" id="exampleRepeatPassword" placeholder="Department" />  
  58.                     </div>  
  59.                   </div>  
  60.                   <button type="submit" class="btn btn-primary  btn-block">  
  61.                     Create User  
  62.                 </button>  
  63.                   <hr />  
  64.                 </form>  
  65.                 <hr />  
  66.               </div>  
  67.             </div>  
  68.           </div>  
  69.         </div>  
  70.       </div>  
  71.     </div>  
  72.   )  
  73. }  
  74.   
  75. export default Regster  
 Now, in Login1.js file, add the following code.
  1. import React, { useState, useEffect } from 'react'   
  2. import axios from 'axios';  
  3. function Login1(props) {  
  4.     const [employee, setemployee] = useState({ Email: ''Password''});  
  5.     const apiUrl = "http://localhost:1680/api/employee/Login";    
  6.     const Login = (e) => {    
  7.             e.preventDefault();    
  8.             debugger;   
  9.             const data = { Email:employee.Email, Password: employee.Password };    
  10.             axios.post(apiUrl, data)    
  11.             .then((result) => {    
  12.                 debugger;  
  13.                 console.log(result.data);   
  14.                 const serializedState = JSON.stringify(result.data.UserDetails);  
  15.                var a= localStorage.setItem('myData', serializedState);   
  16.                 console.log("A:",a)  
  17.                 const user =result.data.UserDetails;  
  18.                 console.log(result.data.message);  
  19.                 if (result.data.status == '200')    
  20.                     props.history.push('/Dashboard')    
  21.                 else    
  22.                 alert('Invalid User');    
  23.             })        
  24.           };    
  25.           
  26.           const onChange = (e) => {    
  27.                 e.persist();    
  28.                 debugger;    
  29.                 setemployee({...employee, [e.target.name]: e.target.value});    
  30.               }    
  31.     return (  
  32.         
  33.         <div class="container">  
  34.         <div class="row justify-content-center">  
  35.           <div class="col-xl-10 col-lg-12 col-md-9">  
  36.             <div class="card o-hidden border-0 shadow-lg my-5">  
  37.               <div class="card-body p-0">  
  38.                 <div class="row">  
  39.                   <div class="col-lg-6 d-none d-lg-block bg-login-image"></div>  
  40.                   <div class="col-lg-6">  
  41.                     <div class="p-5">  
  42.                       <div class="text-center">  
  43.                         <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1>  
  44.                       </div>  
  45.                       <form onSubmit={Login} class="user">  
  46.                         <div class="form-group">  
  47.                           <input type="email" class="form-control" value={employee.Email} onChange={ onChange }  name="Email" id="Email" aria-describedby="emailHelp" placeholder="Enter Email"/>  
  48.                         </div>  
  49.                         <div class="form-group">  
  50.                           <input type="password" class="form-control" value={employee.Password} onChange={ onChange }  name="Password" id="DepPasswordartment" placeholder="Password"/>  
  51.                         </div>  
  52.                         {/* <div class="form-group">  
  53.                           <div class="custom-control custom-checkbox small">  
  54.                             <input type="checkbox" class="custom-control-input" id="customCheck"/>  
  55.                             <label class="custom-control-label" for="customCheck">Remember Me</label>  
  56.                           </div>  
  57.                         </div> */}  
  58.                         <button type="submit" className="btn btn-info mb-1" block><span>Login</span></button>    
  59.                         <hr/>  
  60.                       </form>  
  61.                       <hr/>  
  62.                     </div>  
  63.                   </div>  
  64.                 </div>  
  65.               </div>  
  66.             </div>  
  67.            </div>  
  68.           </div>  
  69.         </div>  
  70.     )  
  71. }  
  72.   
  73. export default Login1  
  Open the Dahboard.js file and add the following code.
  1. import React, { useState, useEffect } from 'react'  
  2.   
  3. function Dashboard() {  
  4.     const [user, setuser] = useState({ Email: ''Password'' });  
  5.     useEffect(() => {  
  6.         var a = localStorage.getItem('myData');  
  7.         var b = JSON.parse(a);  
  8.         console.log(b.EmployeeName);  
  9.         setuser(b)  
  10.         console.log(user.EmployeeName)  
  11.   
  12.     }, []);  
  13.     return (  
  14.         <>  
  15.             <div class="col-sm-12 btn btn-primary">  
  16.                 Dashboard  
  17.         </div>  
  18.             <h1>Welcome :{user.EmployeeName}</h1>  
  19.         </>  
  20.     )  
  21. }  
  22.   
  23. export default Dashboard  
 Open the App.js file and add the folllowing code.
  1. import React from 'react';  
  2. import './App.css';  
  3. import Login1 from "./Login1";  
  4. import Regster from "./Regster";  
  5. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';   
  6. import Dashboard from "./Dashboard";  
  7. function App() {  
  8.   return (  
  9.     <Router>      
  10.       <div className="container">      
  11.         <nav className="navbar navbar-expand-lg navheader">      
  12.           <div className="collapse navbar-collapse" >      
  13.             <ul className="navbar-nav mr-auto">      
  14.               <li className="nav-item">      
  15.                 <Link to={'/login'} className="nav-link">login</Link>      
  16.               </li>    
  17.               <li className="nav-item">      
  18.                 <Link to={'/Regster'} className="nav-link">Regster</Link>      
  19.               </li>    
  20.             </ul>      
  21.           </div>      
  22.         </nav> <br />      
  23.         <Switch>        
  24.           <Route path='/login' component={Login1} />     
  25.           <Route path='/Regster' component={Regster} />    
  26.           <Route path='/Dashboard' component={Dashboard} />  
  27.         </Switch>      
  28.       </div>      
  29.     </Router>     
  30.   );  
  31. }  
  32.   
  33. export default App;  
 Now, run the project by using 'npm start' command and check the result.
 
 
 Enter value and click on 'create user' button.now click on Login button 
 
 Enter email and password and click on Login button.
 

Summary

 
In this article, we discussed the process of Login and Registration page creation in an application using React Hooks and Web API. React Hooks are a new concept that were introduced in React 16.8. Hooks are an alternative to classes.