How To Create A Contact List Using Web API And React

Introduction

 
In this article, we will learn the step by step process of creating an employee contact list using React.js and Web API. React is an open-source JavaScript library that 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 it 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
  • Install Axios

Create a database and table

 
Open SQL Server Management Studio, create a database named ContactManager and in this database, create a table. Give that table a name like contacts
  1. CREATE TABLE [dbo].[contacts](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [Firstname] [nvarchar](50) NULL,    
  4.     [Lastname] [nvarchar](50) NULL,    
  5.     [Phone] [nvarchar](50) NULL,    
  6.     [Email] [nvarchar](50) NULL,    
  7.     [Password] [nvarchar](50) NULL,    
  8.  CONSTRAINT [PK_contacts] 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. GO     

Create a Web API Project

 
Open Visual Studio and create a new project.
 
How To Create A Contact List Using Web API And React
 
Change the name as Employeemanager and Click ok > Select Web API as its template.
 
How To Create A Contact List Using Web API And React
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
How To Create A Contact List Using Web API And React
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
How To Create A Contact List Using Web API And React
 
Select EF Designer from the database and click the "Next" button.
 
How To Create A Contact List Using Web API And React
 
Add the connection properties and select database name on the next page and click OK.
 
How To Create A Contact List Using Web API And React
 
Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
How To Create A Contact List Using Web API And React
 
Our data model is successfully created now.
 
Now, right-click on the Models folder and add a class - createcontact and paste the following code in this class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace Employeemanger.Models  
  7. {  
  8.     public class Createcontact  
  9.     {  
  10.         public int Id { get; set; }  
  11.         public string Firstname { get; set; }  
  12.         public string Lastname { get; set; }  
  13.         public string Phone { get; set; }  
  14.         public string Email { get; set; }  
  15.         public string Password { get; set; }  
  16.     }  
  17. }  
Right-click on the Controllers folder and add a new controller. Name it "Employee controller" and add the following namespace in the Employee controller 
  1. using Employeemanger.Models;  
Now, add a method to insert data into the database.
  1. [Route("Addorupdatecontact")]  
  2.        [HttpPost]  
  3.        public object Addorupdatecontact(Createcontact contact)  
  4.        {  
  5.            contact ct = new contact();  
  6.            ct.Firstname = contact.Firstname;  
  7.            ct.Lastname = contact.Lastname;  
  8.            ct.Phone = contact.Phone;  
  9.            ct.Email = contact.Email;  
  10.            ct.Password = contact.Password;  
  11.            DB.contacts.Add(ct);  
  12.            DB.SaveChanges();  
  13.            return new Response  
  14.            { Status = "Success", Message = "Record SuccessFully Saved." };  
  15.        }  
Add another method to fetch data from the database. 
  1. [Route("employeelist")]  
  2.         [HttpGet]  
  3.         public object employeelist()  
  4.         {  
  5.             return DB.contacts.ToList();  
  6.         }  
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 using the following command.
  1. npx create-react-app contactmanagerapp  
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  
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. Addemployee.js
  2. Employeelist.js
Now, open the Addemployee.js file and add the following code.
  1. import React, { Component } from 'react'  
  2. import axios from 'axios';  
  3. export class Addemployee extends Component {  
  4.   constructor(props) {  
  5.     super(props)  
  6.     this.state = {  
  7.       FirstName: '',  
  8.       LastName: '',  
  9.       Email: '',  
  10.       Phone: '',  
  11.       Password: '',  
  12.     }  
  13.   }  
  14.   Addemployee = () => {  
  15.     debugger;  
  16.     axios.post('http://localhost:2345/api/employee/Addorupdatecontact/', {  
  17.       FirstName: this.state.FirstName, LastName: this.state.LastName,  
  18.       Email: this.state.Email, Phone: this.state.Phone,Password: this.state.Password  
  19.     })  
  20.       .then(json => {  
  21.         if (json.data.Status === 'Success') {  
  22.           console.log(json.data.Status);  
  23.           alert("Data Save Successfully");  
  24.          this.props.history.push('/EmployeeList')  
  25.         }  
  26.         else {  
  27.           alert('Data not Saved');  
  28.           debugger;  
  29.         }  
  30.       })  
  31.   }  
  32.   handleChange= (e)=> {    
  33.     this.setState({[e.target.name]:e.target.value});    
  34.     }   
  35.   render() {  
  36.     return (  
  37.       <div class="container">  
  38.         <div class="row">        
  39.     <div class="col-sm-12 btn btn-primary" style={{"margin":"6px"}}>        
  40.       Add New Contact  
  41.     </div>        
  42.   </div>    
  43.         <div class="card o-hidden border-0 shadow-lg my-5" style={{"marginTop":"5rem!important;"}}>  
  44.           <div class="card-body p-0">  
  45.             <div class="row">  
  46.               <div class="col-lg-12">  
  47.                 <div class="p-5">  
  48.                   <div class="text-center">  
  49.                     <h1 class="h4 text-gray-900 mb-4">Create a New Contact!</h1>  
  50.                   </div>  
  51.                   <form class="user">  
  52.                     <div class="form-group row">  
  53.                       <div class="col-sm-6 mb-3 mb-sm-0">  
  54.                         <input type="text" name="FirstName" onChange={this.handleChange} value={this.state.FirstName} class="form-control" id="exampleFirstName" placeholder="First Name" />  
  55.                       </div>  
  56.                       <div class="col-sm-6">  
  57.                         <input type="text" name="LastName" onChange={this.handleChange} value={this.state.LastName } class="form-control" id="exampleLastName" placeholder="Last Name" />  
  58.                       </div>  
  59.                     </div>  
  60.                     <div class="form-group">  
  61.                       <input type="email" name="Email" onChange={this.handleChange} value={this.state.Email} class="form-control" id="exampleInputEmail" placeholder="Email Address" />  
  62.                     </div>  
  63.                     <div class="form-group row">  
  64.                       <div class="col-sm-6 mb-3 mb-sm-0">  
  65.                         <input type="text" name="Phone" onChange={this.handleChange} value={this.state.Phone} class="form-control" id="exampleInputPassword" placeholder="Phone" />  
  66.                       </div>  
  67.                       <div class="col-sm-6">  
  68.                         <input type="password" name="Password" onChange={this.handleChange} value={this.state.Password} class="form-control" id="exampleRepeatPassword" placeholder="Password" />  
  69.                       </div>  
  70.                     </div>  
  71.                     <button type="button"  onClick={this.Addemployeeclass="btn btn-primary  btn-block">  
  72.                       Create Contact  
  73.                 </button>  
  74.                     <hr />  
  75.                   </form>  
  76.                   <hr />  
  77.                 </div>  
  78.               </div>  
  79.             </div>  
  80.           </div>  
  81.         </div>  
  82.       </div>  
  83.     )  
  84.   }  
  85. }  
  86.   
  87. export default Addemployee  
Now, in Employeelist.js file, add the following code:
  1. import React, { Component } from 'react'  
  2. import axios from 'axios'  
  3. export class EmployeeList extends Component {  
  4.   constructor(props) {  
  5.     super(props)  
  6.     this.state = {  
  7.       Employeelist: []  
  8.     }  
  9.   }  
  10.   componentDidMount() {  
  11.     axios.get('http://localhost:2345/api/employee/employeelist').then(response => {  
  12.       console.log(response.data);  
  13.       this.setState({  
  14.         Employeelist: response.data  
  15.       });  
  16.     });  
  17.   }  
  18.   render() {  
  19.     const items = []  
  20.     for (const [index, value] of this.state.Employeelist.entries()) {  
  21.       items.push(<li key={index}>{value}</li>)  
  22.     }  
  23.     return (  
  24.   
  25.       <div class="container-fluid">  
  26.         <div class="row">  
  27.           <div class="col-sm-12 btn btn-primary" style={{ "margin""6px" }}>  
  28.             Contact List  
  29.     </div>  
  30.         </div>  
  31.         <div class="row">  
  32.           {  
  33.             this.state.Employeelist.map((p, index) => {  
  34.               return <div key={index} class="col-xl-3 col-md-6 mb-4">  
  35.                 <div class="card">  
  36.                   <div class="card-header py-3">  
  37.                     <h6 class="m-0 font-weight-bold text-primary">  <img style={{ "height""25px" }} src="https://img.icons8.com/nolan/64/contact-card.png" />Contact Details</h6>  
  38.                   </div>  
  39.                   <div class="card-body">  
  40.                     <div class="row no-gutters align-items-center">  
  41.                       <div class="form-group row">  
  42.                         <div class="col-sm-12">  
  43.                           <div class="row">  
  44.                             <div class="col-sm-2">  
  45.                               <img src="https://img.icons8.com/office/16/000000/user.png" />  
  46.                             </div>  
  47.                             <div class="col-sm-8 col mr-2">  
  48.                               {p.Firstname + '  ' + p.Lastname}  
  49.                             </div>  
  50.                           </div>  
  51.                         </div>  
  52.                         <div class="col-sm-12">  
  53.                           <div class="row">  
  54.                             <div class="col-sm-2">  
  55.                               <img style={{ "height""20px" }} src="https://img.icons8.com/nolan/64/email.png" />  
  56.                             </div>  
  57.                             <div class="col-sm-10">  
  58.                               {p.Email}  
  59.                             </div>  
  60.                             <div class="col-sm-2"></div>  
  61.                           </div>  
  62.                         </div>  
  63.                         <div class="col-sm-12">  
  64.                           <div class="row">  
  65.                             <div class="col-sm-2">  
  66.                               <img style={{ "height""20px" }} src="https://img.icons8.com/nolan/64/phone.png" />  
  67.                             </div>  
  68.                             <div class="col-sm-8">  
  69.                               {p.Phone}  
  70.                             </div>  
  71.                           </div>  
  72.                         </div>  
  73.                       </div>  
  74.                     </div>  
  75.                   </div>  
  76.                 </div>  
  77.               </div>  
  78.             })  
  79.           }  
  80.         </div>  
  81.       </div>  
  82.     )  
  83.   }  
  84. }  
  85.   
  86. export default EmployeeList  
Open the App.js file and add the following code.
  1. import React from 'react';  
  2. import './App.css';  
  3. import EmployeeList from './EmployeeList'  
  4. import Addemployee from './Addemployee'  
  5. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';   
  6. function App() {  
  7.   return (  
  8.     <Router>      
  9.       <div className="container">      
  10.         <nav className="navbar navbar-expand-lg navheader">      
  11.           <div className="collapse navbar-collapse" >      
  12.             <ul className="navbar-nav mr-auto">      
  13.               <li className="nav-item">      
  14.                 <Link to={'/EmployeeList'} className="nav-link">Contact List</Link>      
  15.               </li>      
  16.               <li className="nav-item">      
  17.                 <Link to={'/Addemployee'} className="nav-link">Add Contact</Link>      
  18.               </li>      
  19.             </ul>      
  20.           </div>      
  21.         </nav> <br />      
  22.         <Switch>      
  23.           <Route exact path='/' component={EmployeeList} />      
  24.           <Route exact path='/EmployeeList' component={EmployeeList} />      
  25.           <Route path='/Addemployee' component={Addemployee} />     
  26.         </Switch>      
  27.       </div>      
  28.     </Router>     
  29.   );  
  30. }  
  31.   
  32. export default App;  
Now, run the project by using 'npm start' command and check the result.
How To Create A Contact List Using Web API And React
 
Enter the values, click on Create contact button and check
How To Create A Contact List Using Web API And React 

Summary

 
In this article, we learned the step by step process of creating an employee contact list using React.js and Web API.


Similar Articles