How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API

In this article, I am going to create an application to get user details in a model popup in React JS with Axios using Web API.

Introduction 

 
In this article, I'm going to create an application to get user details in a model popup in ReactJS with Axios using Web API with the help of an example SQL Server database as back-end. A Web API is used to provide data connectivity between the database and the front-end application for building RESTful services.
 
On the UI side, I will use bootstrap to create a rich, interactive, device-independent user experience so as to building a beautiful UI. In this example, I will bind user details in a short format ( i.e. will see only necessary columns) and when we want to see the records in detail of a particular user, then will click a specific row. After that, it will show records in a popup window and then clicking the Close button will close the popup. Let us see step by step.
 
I'm using Visual Studio Code as a tool to build my application. If you don't have Visual Studio Code in your system, then first you have to download and install. Here is the Visual Studio Code download link: Download Visual Studio Code Editor.
 
Prerequisites
  1. Visual Studio
  2. SQL Server
  3. JavaScript version > 10
  4. React
  5. React Axios
  6. Visual Studio Code
  7. Bootstrap
  8. React-bootstrap
Step 1 - Create a database and table
 
Create a database. Open SQL Server and create a new database and table. As you can see from the following query, I have created the database tables called Branch Details and Company Details.
 
UserDetails 
  1. CREATE TABLE [dbo].[UserDetails](  
  2.     [UserId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FirstName] [varchar](50) NULL,  
  4.     [LastName] [varchar](50) NULL,  
  5.     [EmailId] [varchar](100) NULL,  
  6.     [MobileNo] [varchar](50) NULL,  
  7.     [Address] [varchar](500) NULL,  
  8.     [PinCode] [char](10) NULL,  
  9.     [CompanyName] [varchar](100) NULL,  
  10.     [Gender] [nchar](20) NULL,  
  11.     [Country] [varchar](50) NULL,  
  12.     [State] [varchar](100) NULL,  
  13.     [City] [varchar](100) NULL,  
  14.  CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED   
  15. (  
  16.     [UserId] ASC  
  17. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  18. ON [PRIMARY]  
  19.   
  20. GO  
  21. SET ANSI_PADDING OFF  
  22. GO  
  23. SET IDENTITY_INSERT [dbo].[UserDetails] ON   
  24.   
  25. INSERT [dbo].[UserDetails] VALUES (2, N'Mithilesh', N'kumar', N'mithilesh@gmail.com', N'3049583043', N'hyderabad', N'039458    ', N'Microsoft', N'Male, ', N'India', N'Telangana', N'Hyderabad')  
  26. INSERT [dbo].[UserDetails] VALUES (23, N'Suresh', N'Sura', N'suresh@gmail.com', N'9485034934', N'pune', N'346344    ', N'TSC', N'Male', N'India', N'Karnatak', N'Banglore')  
  27. INSERT [dbo].[UserDetails] VALUES (24, N'Mona', N'Sharma', N'mona@gmail.com', N'0982349335', N'Pune', N'893484    ', N'HCL', N'Female', N'India', N'Mahrastra', N'Pune')  
  28. INSERT [dbo].[UserDetails] VALUES (25, N'Neha', N'Bharti', N'neha@gmail.com', N'2495304444', N'Chennai', N'938459    ', N'Bipro', N'Female', N'India', N'TamilNadu', N'Chennai')  
  29. SET IDENTITY_INSERT [dbo].[UserDetails] OFF  
Note
You can choose the size of the columns according to your requirement.
 
Step 2 - Create a Web API Project

Now, we will create a Web API with the functionality of binding records from a database. Go to Visual Studio >> File >> New >> Project, and select Web Application. after that, click OK and you will see the templates. Select the Web API template.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Click OK.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Click OK.
 
Step 3 - Add ADO.NET Entity Data Model
 
Now, select the Models folder. Right-click on it and go to Add >> New Item >> select Data in left panel >> ADO.NET Entity Data Model.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Click "Add".
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Click the "Next" button.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Give server name of SQL Server and its credentials. Then, select the database and test connection. Click OK.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Click the "Next" button.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Select tables and click the "Finish" button.
 
Let us see our table entity.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Step 4 - Add API controller logic
 
Go to the Controller folder in the API Application and right-click >> Add >> Controller >> Select Web API 2 Controller-Empty.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Click the "Add" button.
 
Now, we will write the logic for performing the CRUD operation. We will go to the Controller class and set the routing to make it more user-friendly by writing the below code.
  1. using System;  
  2. using System.Linq;  
  3. using System.Web.Http;  
  4. using ReactCRUDApi.Models;  
  5.   
  6. namespace ReactCRUDApi.Controllers  
  7. {  
  8.     [RoutePrefix("Api/User")]  
  9.     public class UserController : ApiController  
  10.     {  
  11.         ReactDBEntities objEntity = new ReactDBEntities();  
  12.   
  13.         [HttpGet]  
  14.         [Route("GetUserDetails")]  
  15.         public IQueryable<UserDetail> GetEmaployee()  
  16.         {  
  17.             try  
  18.             {  
  19.                 return objEntity.UserDetails;  
  20.             }  
  21.             catch (Exception)  
  22.             {  
  23.                 throw;  
  24.             }  
  25.         }  
  26.   
  27.         [HttpGet]  
  28.         [Route("GetUserDetailsById/{userId}")]  
  29.         public IHttpActionResult GetUserById(string userId)  
  30.         {  
  31.             UserDetail objUser = new UserDetail();  
  32.             if (userId != "undefined")  
  33.             {  
  34.                 
  35.                 int ID = Convert.ToInt32(userId);  
  36.                 try  
  37.                 {  
  38.                     objUser = objEntity.UserDetails.Find(ID);  
  39.                     if (objUser == null)  
  40.                     {  
  41.                         return NotFound();  
  42.                     }  
  43.   
  44.                 }  
  45.                 catch (Exception)  
  46.                 {  
  47.                     throw;  
  48.                 }  
  49.             }  
  50.   
  51.             return Ok(objUser);  
  52.         }  
  53.     }  
  54. }  
Now, our API has been completed and as you may see from the above code, it has the functionality to GetAll and GetById records to the table.
 
Step 5 - Create and Install React.js
 
Now, we will create a React project through the below command. But before that, just check if Node and NPM are installed or not. And also, since we are using Visual Studio Code for writing Angular code for UI application, so first, make sure it is installed. If you have not installed the VS Code, then go to this link for download.
 
Let's create a React project. Open a new terminal and run the following command to install and create a React project.
 
npx create-react-app modelexample
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
React project has been created successfully.
 
Step 6 - Set Visual Studio Code for React code
 
Open Visual Studio Code and open the project inside it.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Select the project folder.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Step 7 - Check React dependency
 
Go to the package.json file and check for React dependency.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Step 8 - Generate React Component
 
Go inside the src folder and create a new folder. Here, I have created a ModelDemo folder and created 2 files - Action.js and Modal.js.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Step 9 - Install bootstrap
 
Now, we will install bootstrap for building a beautiful UI of our React application.
 
npm install bootstrap --save
 
And next, we will install react-bootstrap bootstrap for design table, button, etc
 
npm install react-bootstrap bootstrap
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Step 10 - Install Axios library
 
Axios is a modern and promise based JavaScript HTTP client library which works asynchronously and allows us to make HTTP calls and consume REST API.
 
Now, let's install Axios in our React project using the following command.
 
npm install --save axios
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Step 11 - Write code in the JS file to perform our operation
 
Now, we will write our logic for performing CRUD operation. First, we will write code to get user details.
 
Go inside the ModelDemo folder and open Modal.js file. In this file, we will create a model for populate particular records and design our popup window.
  1. import React from 'react';  
  2. import PropTypes from 'prop-types';  
  3.   
  4. class Modal extends React.Component {  
  5.   render() {  
  6.      
  7.     if(!this.props.show) {  
  8.       return null;  
  9.     }  
  10.      
  11.     const backdropStyle = {  
  12.       position: 'fixed',  
  13.       top: 50,  
  14.       bottom: 0,  
  15.       left: 0,  
  16.       right: 0,  
  17.       backgroundColor: 'rgba(0,0,0,0.3)',  
  18.       padding: 50,  
  19.       
  20.     };  
  21.   
  22.  const model = {  
  23.   position: 'relative',  
  24.   top: 0,  
  25.   left: 0,  
  26.   display: 'table',  
  27.   Width: '100%',  
  28.   height: '30%',  
  29.   overflow: 'hidden',  
  30.   outline: 0,  
  31.   backgroundColor: '#fff',  
  32.   margin: '0 auto',  
  33.   padding: 10,  
  34.   maxWidth: 500,  
  35.   minHeight: 300,  
  36.  };  
  37.   
  38.     return (  
  39.       <div className="backdrop" style={backdropStyle}>  
  40.         <div className="modal" style={model}>  
  41.           {this.props.children}  
  42.   
  43.           <div className="footer">  
  44.             <button className="btn-warning" onClick={this.props.onClose}>  
  45.               Close  
  46.             </button>  
  47.           </div>  
  48.         </div>  
  49.       </div>  
  50.     );  
  51.   }  
  52. }  
  53.   
  54. Modal.propTypes = {  
  55.   onClose: PropTypes.func.isRequired,  
  56.   show: PropTypes.bool,  
  57.   children: PropTypes.node  
  58. };  
  59.   
  60. export default Modal;  
Now, again go inside the ModelDemo folder and open Action.js file. First, import necessary libraries and then write the below code. In this file, I will create two methods - first for selecting short details and second for selecting particular user details. And in the Render section, we will take a table for displaying user short details and Model for displaying particular details in the popup,
  1. import React, { Component } from 'react';  
  2. import Modal from './Modal';  
  3.   
  4. import axios from 'axios';  
  5. import { Table,Button } from 'react-bootstrap';  
  6. const apiUrl = 'http://localhost:51971/Api/User';  
  7.   
  8. class App extends Component {  
  9.   constructor(props) {  
  10.     super(props);  
  11.   
  12.     this.state = {  
  13.       isOpen: false,  
  14.       error: null,  
  15.       users: [],  
  16.       userData: {},  
  17.       response: {}  
  18.     };  
  19.   }  
  20.   
  21.   componentDidMount(){  
  22.     axios.get(apiUrl + '/GetUserDetails').then(response => response.data).then(  
  23.          (result)=>{  
  24.              this.setState({  
  25.                  users:result  
  26.              });  
  27.          },  
  28.          (error)=>{  
  29.              this.setState({error});  
  30.          }  
  31.      )  
  32.  }  
  33.   
  34.   toggleModal(userId) {  
  35.   
  36. axios.get(apiUrl + "/GetUserDetailsById/" + userId).then(response => response.data).then(result => {  
  37.   
  38.          this.setState({  
  39.           userData: result        
  40.          });  
  41.        },  
  42.        (error) => {  
  43.          this.setState({ error });  
  44.        }  
  45.      )  
  46.   
  47.      this.setState({  
  48.       isOpen: !this.state.isOpen  
  49.     });  
  50.    
  51.   }  
  52.   
  53.   render() {  
  54.     const{users}=this.state;  
  55.     return (  
  56.       <div className="App">  
  57.     
  58.         <div >  
  59. <div className="row">  
  60. <div className="col-md-3"></div>  
  61. <div className="col-md-6">  
  62. <Table className="table">  
  63.                     <thead className="btn-primary">  
  64.                       <tr>  
  65.                         <th>First Name</th>                       
  66.                         <th>EmailId</th>  
  67.                         <th>MobileNo</th>  
  68.                         <th>Action</th>  
  69.                       </tr>  
  70.                     </thead>  
  71.                     <tbody>  
  72.                       {users.map(user => (  
  73.                         <tr key={user.UserId}>  
  74.                           <td>{user.FirstName}</td>  
  75.                        
  76.                           <td>{user.EmailId}</td>  
  77.                           <td>{user.MobileNo}</td>  
  78.                           
  79.                           <td><Button variant="info" onClick={()=>this.toggleModal(user.UserId)} >Details</Button>       
  80.                           
  81.                           </td>  
  82.                         </tr>  
  83.                       ))}  
  84.                     </tbody>  
  85.                   </Table>  
  86. </div>  
  87. <div className="col-md-3"></div>  
  88. </div>  
  89.       
  90.                   </div>  
  91.         <Modal show={this.state.isOpen}  
  92.           onClose={()=>this.toggleModal(this.UserId)}>  
  93.           <Table className="table">  
  94.             <thead>  
  95.               <tr className="btn-primary"><th colSpan="2">User Details</th></tr>  
  96.             </thead>  
  97.             <tbody>  
  98.   
  99.               <tr>  
  100.                 <th>First Name </th><td>{this.state.userData.FirstName}</td>  
  101.               </tr> <tr>  
  102.                 <th>Last Name </th><td>{this.state.userData.LastName}</td>  
  103.               </tr> <tr>  
  104.                 <th>EmailId  </th><td>{this.state.userData.EmailId}</td>  
  105.               </tr> <tr>  
  106.                 <th>Mobile No  </th><td>{this.state.userData.MobileNo}</td>  
  107.               </tr> <tr>  
  108.                 <th>Address  </th><td>{this.state.userData.Address}</td>  
  109.               </tr> <tr>  
  110.                 <th>PinCode  </th><td>{this.state.userData.PinCode}</td>  
  111.               </tr>  
  112.               <tr>  
  113.                 <th>Company Name  </th><td>{this.state.userData.CompanyName}</td>  
  114.               </tr>  
  115.               <tr>  
  116.                 <th>Gender  </th><td>{this.state.userData.Gender}</td>  
  117.               </tr>  
  118.               <tr>  
  119.                 <th>Country  </th><td>{this.state.userData.Country}</td>  
  120.               </tr>  
  121.               <tr>  
  122.                 <th>State  </th><td>{this.state.userData.State}</td>  
  123.               </tr>  
  124.               <tr>  
  125.                 <th>City  </th><td>{this.state.userData.City}</td>  
  126.               </tr>  
  127.             </tbody>  
  128.           </Table>  
  129.                  
  130.         </Modal>  
  131.       </div>  
  132.     );  
  133.   }  
  134. }  
  135.   
  136. export default App;  
Lastly, open the index.js file, import necessary library, and write the below code.
  1. import React from 'react';  
  2. import './App.css';  
  3. import Action from './ModelDemo/Action';  
  4. import '../node_modules/bootstrap/dist/css/bootstrap.min.css';  
  5.   
  6. function App() {  
  7.   return (  
  8.     <div className="App">  
  9.      <Action/>  
  10.     </div>  
  11.   );  
  12. }  
  13.   
  14. export default App;  
Finally, our coding part also has been completed.
 
Step 16 - Set CORS (Cross-Origin Resource Sharing)
 
Go to the Web API project.
 
Download a NuGet package for CORS. Go to NuGet Package Manager and download the following file.
 
After that, go to the App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Add namespace
  1. using System.Web.Http.Cors;  
After that, add the below code inside Register method.
  1. var cors = new EnableCorsAttribute("*""*""*");  
  2. config.EnableCors(cors);  
Step 17 - Run
 
We have completed all the needed code functionality for our functionality. Before running the application, first, make sure to save your work.
 
Now, let's run the app and see how it works. 
 
Open TERMINAL and write the following command to run the program.
 
npm start
 
The output looks like the following image. It's a stunning UI that's been created.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Now, click on the "Details" button.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 
Now, take a look at the final operation.
 
How To Create An Application To Get User Details In A Model Popup In ReactJS With Axios Using Web API
 

Conclusion

 
We have learned how to perform an operation to get the details of a particular user in popup or model dialogs in React and Axios using Web API and SQL Server. We started by installing and creating the create-react-app then used it to create our React project. Next, we installed bootstrap and react-bootstrap in the React application. After that, we installed the Axios client library and used the get() details and particular get details methods to the HTTP request.
 
I hope you enjoyed this article. Always willing to reply to any query and comment.