Create User Registration And Login Using Web API And ReactJS

Introduction 

 
In this article, we will learn the step by step process of creating user registration and login pages using React.js and Web API. React is an open-source JavaScript library which is used for creating user interfaces particularly for single-page applications. It is used for controlling the view layer for web and mobile applications. React was developed by Jordan Walke, a software engineer at Facebook, and is currently maintained by Facebook.
 
Prerequisites 
  • Basic knowledge of React.js and Web API
  • Visual Studio
  • Visual Studio Code 
  • SQL Server Management Studio
  • Node.js
This article covers the following:
  • Create a database and table
  • Create a Web API Project
  • Create React Project
  • Install Bootstrap and React strap
  • Add Routing 
If you're new to react, start here: Introduction to React Step by Step Guide
 

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.
 
Create User Registration And Login Using Web API And ReactJS
 
Change the name as LoginApplication and Click ok > Select Web API as its template.
 
Create User Registration And Login Using Web API And ReactJS
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
Create User Registration And Login Using Web API And ReactJS
 
Click on the "ADO.NET Entity Data Model" option and click "Add".>Select EF Designer from the database and click the "Next" button.
 
Create User Registration And Login Using Web API And ReactJS
 
Add the connection properties and select database name on the next page and click OK.
 
Create User Registration And Login Using Web API And ReactJS
 
Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
Create User Registration And Login Using Web API And ReactJS
 
Our data model is successfully created now.
 
Now, add a new folder named VM. Right-click on the VM 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 { getset; }  
  4.        public string Password { getset; }  
  5.    }  
Register Class
  1. public class Register  
  2.   {  
  3.       public int Id { getset; }  
  4.       public string Email { getset; }  
  5.       public string Password { getset; }  
  6.       public string EmployeeName { getset; }  
  7.       public string City { getset; }  
  8.       public string Department { getset; }  
  9.   }  
Response Class
  1. public class Response  
  2.    {  
  3.        public string Status { setget; }  
  4.        public string Message { setget; }  
  5.   
  6.    }  
Right-click on the Controllers folder and add a new controller. Name it as "Login controller" and add following namespaces.
  1. using LoginApplication.Models;  
  2. using LoginApplication.VM;  
Create two methods in this controller to insert 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 LoginApplication.Models;  
  8. using LoginApplication.VM;  
  9.   
  10. namespace LoginApplication.Controllers  
  11. {  
  12.     [RoutePrefix("Api/login")]  
  13.     public class LoginController : ApiController  
  14.     {  
  15.         EmployeesEntities DB = new EmployeesEntities();  
  16.         [Route("InsertEmployee")]  
  17.         [HttpPost]  
  18.         public object InsertEmployee(Register Reg)  
  19.         {  
  20.             try  
  21.             {  
  22.   
  23.                 EmployeeLogin EL = new EmployeeLogin();  
  24.                 if (EL.Id == 0)  
  25.                 {  
  26.                     EL.EmployeeName = Reg.EmployeeName;  
  27.                     EL.City = Reg.City;  
  28.                     EL.Email = Reg.Email;  
  29.                     EL.Password = Reg.Password;  
  30.                     EL.Department = Reg.Department;  
  31.                     DB.EmployeeLogins.Add(EL);  
  32.                     DB.SaveChanges();  
  33.                     return new Response  
  34.                     { Status = "Success", Message = "Record SuccessFully Saved." };  
  35.                 }  
  36.             }  
  37.             catch (Exception)  
  38.             {  
  39.   
  40.                 throw;  
  41.             }  
  42.             return new Response  
  43.             { Status = "Error", Message = "Invalid Data." };  
  44.         }  
  45.         [Route("Login")]  
  46.         [HttpPost]  
  47.         public Response employeeLogin(Login login)  
  48.         {  
  49.             var log = DB.EmployeeLogins.Where(x => x.Email.Equals(login.Email) && x.Password.Equals(login.Password)).FirstOrDefault();  
  50.   
  51.             if (log == null)  
  52.             {  
  53.                 return new Response { Status = "Invalid", Message = "Invalid User." };  
  54.             }  
  55.             else  
  56.                 return new Response { Status = "Success", Message = "Login Successfully" };  
  57.         }  
  58.     }  
  59. }  
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 loginapp    
Open the newly created project in visual studio code and install reactstrap and bootstrap in this project by using the following command
  1. npm install --save bootstrap      
  2. npm install --save reactstrap react react-dom     
 Use the following command to add routing in React
  1. npm install react-router-dom --save  
Now go to src folder and add 3 new components.
  1. Login.js
  2. Reg.js
  3. Dashboard.js
Now, open the Reg.js file and add the following code.
  1. import React, { Component } from 'react';  
  2. import { Button, Card, CardFooter, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
  3.   
  4. class Reg extends Component {  
  5.   
  6.   constructor() {  
  7.     super();  
  8.   
  9.     this.state = {  
  10.       EmployeeName: '',  
  11.       City: '',  
  12.       Email: '',  
  13.       Password: '',  
  14.       Department: ''  
  15.     }  
  16.   
  17.      
  18.     this.Email = this.Email.bind(this);  
  19.     this.Password = this.Password.bind(this);  
  20.     this.EmployeeName = this.EmployeeName.bind(this);  
  21.     this.Password = this.Password.bind(this);  
  22.     this.Department = this.Department.bind(this);  
  23.     this.City = this.City.bind(this);  
  24.     this.register = this.register.bind(this);  
  25.   }  
  26.   
  27.   
  28.   
  29.   Email(event) {  
  30.     this.setState({ Email: event.target.value })  
  31.   }  
  32.   
  33.   Department(event) {  
  34.     this.setState({ Department: event.target.value })  
  35.   }  
  36.   
  37.   Password(event) {  
  38.     this.setState({ Password: event.target.value })  
  39.   }  
  40.   City(event) {  
  41.     this.setState({ City: event.target.value })  
  42.   }  
  43.   EmployeeName(event) {  
  44.     this.setState({ EmployeeName: event.target.value })  
  45.   }  
  46.   
  47.   register(event) {  
  48.   
  49.     fetch('http://localhost:51282/Api/login/InsertEmployee', {  
  50.       method: 'post',  
  51.       headers: {  
  52.         'Accept''application/json',  
  53.         'Content-Type''application/json'  
  54.       },  
  55.       body: JSON.stringify({  
  56.   
  57.   
  58.         EmployeeName: this.state.EmployeeName,  
  59.         Password: this.state.Password,  
  60.         Email: this.state.Email,  
  61.         City: this.state.City,  
  62.         Department: this.state.Department  
  63.       })  
  64.     }).then((Response) => Response.json())  
  65.       .then((Result) => {  
  66.         if (Result.Status == 'Success')  
  67.                 this.props.history.push("/Dashboard");  
  68.         else  
  69.           alert('Sorrrrrry !!!! Un-authenticated User !!!!!')  
  70.       })  
  71.   }  
  72.   
  73.   render() {  
  74.   
  75.     return (  
  76.       <div className="app flex-row align-items-center">  
  77.         <Container>  
  78.           <Row className="justify-content-center">  
  79.             <Col md="9" lg="7" xl="6">  
  80.               <Card className="mx-4">  
  81.                 <CardBody className="p-4">  
  82.                   <Form>  
  83.                     <div class="row" className="mb-2 pageheading">  
  84.                       <div class="col-sm-12 btn btn-primary">  
  85.                         Sign Up  
  86.                         </div>  
  87.                     </div>  
  88.                     <InputGroup className="mb-3">  
  89.                       <Input type="text"  onChange={this.EmployeeName} placeholder="Enter Employee Name" />  
  90.                     </InputGroup>  
  91.                     <InputGroup className="mb-3">  
  92.                       <Input type="text"  onChange={this.Email} placeholder="Enter Email" />  
  93.                     </InputGroup>  
  94.                     <InputGroup className="mb-3">  
  95.                       <Input type="password"  onChange={this.Password} placeholder="Enter Password" />  
  96.                     </InputGroup>  
  97.                     <InputGroup className="mb-4">  
  98.                       <Input type="text"  onChange={this.City} placeholder="Enter City" />  
  99.                     </InputGroup>  
  100.                     <InputGroup className="mb-4">  
  101.                       <Input type="text"  onChange={this.Department} placeholder="Enter Department" />  
  102.                     </InputGroup>  
  103.                     <Button  onClick={this.register}  color="success" block>Create Account</Button>  
  104.                   </Form>  
  105.                 </CardBody>  
  106.               </Card>  
  107.             </Col>  
  108.           </Row>  
  109.         </Container>  
  110.       </div>  
  111.     );  
  112.   }  
  113. }  
  114.   
  115. export default Reg; 
Now, in Login.js file, add the following code.
  1. import React, { Component } from 'react';  
  2. import './App.css';  
  3. import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
  4. class Login extends Component {  
  5.     constructor() {  
  6.         super();  
  7.   
  8.         this.state = {  
  9.             Email: '',  
  10.             Password: ''  
  11.         }  
  12.   
  13.         this.Password = this.Password.bind(this);  
  14.         this.Email = this.Email.bind(this);  
  15.         this.login = this.login.bind(this);  
  16.     }  
  17.   
  18.     Email(event) {  
  19.         this.setState({ Email: event.target.value })  
  20.     }  
  21.     Password(event) {  
  22.         this.setState({ Password: event.target.value })  
  23.     }  
  24.     login(event) {  
  25.         debugger;  
  26.         fetch('http://localhost:51282/Api/login/Login', {  
  27.             method: 'post',  
  28.             headers: {  
  29.                 'Accept''application/json',  
  30.                 'Content-Type''application/json'  
  31.             },  
  32.             body: JSON.stringify({  
  33.                 Email: this.state.Email,  
  34.                 Password: this.state.Password  
  35.             })  
  36.         }).then((Response) => Response.json())  
  37.             .then((result) => {  
  38.                 console.log(result);  
  39.                 if (result.Status == 'Invalid')  
  40.                     alert('Invalid User');  
  41.                 else  
  42.                     this.props.history.push("/Dashboard");  
  43.             })  
  44.     }  
  45.   
  46.     render() {  
  47.   
  48.         return (  
  49.             <div className="app flex-row align-items-center">  
  50.                 <Container>  
  51.                     <Row className="justify-content-center">  
  52.                         <Col md="9" lg="7" xl="6">  
  53.   
  54.                             <CardGroup>  
  55.                                 <Card className="p-2">  
  56.                                     <CardBody>  
  57.                                         <Form>  
  58.                                             <div class="row" className="mb-2 pageheading">  
  59.                                                 <div class="col-sm-12 btn btn-primary">  
  60.                                                     Login  
  61.                              </div>  
  62.                                             </div>  
  63.                                             <InputGroup className="mb-3">  
  64.   
  65.                                                 <Input type="text" onChange={this.Email} placeholder="Enter Email" />  
  66.                                             </InputGroup>  
  67.                                             <InputGroup className="mb-4">  
  68.   
  69.                                                 <Input type="password" onChange={this.Password} placeholder="Enter Password" />  
  70.                                             </InputGroup>  
  71.                                             <Button onClick={this.login} color="success" block>Login</Button>  
  72.                                         </Form>  
  73.                                     </CardBody>  
  74.                                 </Card>  
  75.                             </CardGroup>  
  76.                         </Col>  
  77.                     </Row>  
  78.                 </Container>  
  79.             </div>  
  80.         );  
  81.     }  
  82. }  
  83.   
  84. export default Login;  
Open the Dahboard.js file and add the following code.
  1. import React, { Component } from 'react';  
  2. import './App.css';  
  3. import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
  4.   class Dashboard extends Component {  
  5.     render() {  
  6.   
  7.         return (  
  8.             <div class="row" className="mb-2 pageheading">  
  9.                 <div class="col-sm-12 btn btn-primary">  
  10.                     Dashboard   
  11.              </div>  
  12.             </div>  
  13.         );  
  14.     }  
  15. }  
  16.   
  17. export default Dashboard;  
Open the App.css file and add the following CSS code.
  1. .App {      
  2.   text-align: center;      
  3. }      
  4. .navheader{      
  5.   margin-top: 10px;      
  6.   color :black !important;      
  7.   background-color: #b3beca!important      
  8. }    
  9.   
  10. .PageHeading      
  11. {      
  12.   margin-top: 10px;      
  13.   margin-bottom: 10px;      
  14.   color :black !important;      
  15. }    
Open the App.js file and add the folllowing code.
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import Login from './Login';  
  5. import Reg from './Reg';  
  6. import Dashboard from './Dashboard';  
  7. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';   
  8. function App() {  
  9.   return (  
  10.     <Router>    
  11.       <div className="container">    
  12.         <nav className="navbar navbar-expand-lg navheader">    
  13.           <div className="collapse navbar-collapse" >    
  14.             <ul className="navbar-nav mr-auto">    
  15.               <li className="nav-item">    
  16.                 <Link to={'/Login'} className="nav-link">Login</Link>    
  17.               </li>    
  18.               <li className="nav-item">    
  19.                 <Link to={'/Signup'} className="nav-link">Sign Up</Link>    
  20.               </li>    
  21.                
  22.             </ul>    
  23.           </div>    
  24.         </nav> <br />    
  25.         <Switch>    
  26.           <Route exact path='/Login' component={Login} />    
  27.           <Route path='/Signup' component={Reg} />    
  28.        
  29.         </Switch>    
  30.         <Switch>  
  31.         <Route path='/Dashboard' component={Dashboard} />    
  32.         </Switch>  
  33.       </div>    
  34.     </Router>   
  35.   );  
  36. }  
  37.   
  38. export default App;  
Now, run the project by using 'npm start' command and check the result.
 
Create User Registration And Login Using Web API And ReactJS
 
Enter the details and click on the Login button.
 
Create User Registration And Login Using Web API And ReactJS

Summary

 
In this article, we discussed the process of Login and Registration page creation in an application using React and Web API.