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
- Visual Studio
- SQL Server
- JavaScript version > 10
- React
- React Axios
- Visual Studio Code
- Bootstrap
- 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
- CREATE TABLE [dbo].[UserDetails](
- [UserId] [int] IDENTITY(1,1) NOT NULL,
- [FirstName] [varchar](50) NULL,
- [LastName] [varchar](50) NULL,
- [EmailId] [varchar](100) NULL,
- [MobileNo] [varchar](50) NULL,
- [Address] [varchar](500) NULL,
- [PinCode] [char](10) NULL,
- [CompanyName] [varchar](100) NULL,
- [Gender] [nchar](20) NULL,
- [Country] [varchar](50) NULL,
- [State] [varchar](100) NULL,
- [City] [varchar](100) NULL,
- CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED
- (
- [UserId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
- SET ANSI_PADDING OFF
- GO
- SET IDENTITY_INSERT [dbo].[UserDetails] ON
-
- INSERT [dbo].[UserDetails] VALUES (2, N'Mithilesh', N'kumar', N'[email protected]', N'3049583043', N'hyderabad', N'039458 ', N'Microsoft', N'Male, ', N'India', N'Telangana', N'Hyderabad')
- INSERT [dbo].[UserDetails] VALUES (23, N'Suresh', N'Sura', N'[email protected]', N'9485034934', N'pune', N'346344 ', N'TSC', N'Male', N'India', N'Karnatak', N'Banglore')
- INSERT [dbo].[UserDetails] VALUES (24, N'Mona', N'Sharma', N'[email protected]', N'0982349335', N'Pune', N'893484 ', N'HCL', N'Female', N'India', N'Mahrastra', N'Pune')
- INSERT [dbo].[UserDetails] VALUES (25, N'Neha', N'Bharti', N'[email protected]', N'2495304444', N'Chennai', N'938459 ', N'Bipro', N'Female', N'India', N'TamilNadu', N'Chennai')
- 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.
Click OK.
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.
Click "Add".
Click the "Next" button.
Give server name of SQL Server and its credentials. Then, select the database and test connection. Click OK.
Click the "Next" button.
Select tables and click the "Finish" button.
Let us see our table entity.
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.
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.
- using System;
- using System.Linq;
- using System.Web.Http;
- using ReactCRUDApi.Models;
-
- namespace ReactCRUDApi.Controllers
- {
- [RoutePrefix("Api/User")]
- public class UserController : ApiController
- {
- ReactDBEntities objEntity = new ReactDBEntities();
-
- [HttpGet]
- [Route("GetUserDetails")]
- public IQueryable<UserDetail> GetEmaployee()
- {
- try
- {
- return objEntity.UserDetails;
- }
- catch (Exception)
- {
- throw;
- }
- }
-
- [HttpGet]
- [Route("GetUserDetailsById/{userId}")]
- public IHttpActionResult GetUserById(string userId)
- {
- UserDetail objUser = new UserDetail();
- if (userId != "undefined")
- {
-
- int ID = Convert.ToInt32(userId);
- try
- {
- objUser = objEntity.UserDetails.Find(ID);
- if (objUser == null)
- {
- return NotFound();
- }
-
- }
- catch (Exception)
- {
- throw;
- }
- }
-
- return Ok(objUser);
- }
- }
- }
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
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.
Select the project folder.
Step 7 - Check React dependency
Go to the package.json file and check for React dependency.
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.
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
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
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.
- import React from 'react';
- import PropTypes from 'prop-types';
-
- class Modal extends React.Component {
- render() {
-
- if(!this.props.show) {
- return null;
- }
-
- const backdropStyle = {
- position: 'fixed',
- top: 50,
- bottom: 0,
- left: 0,
- right: 0,
- backgroundColor: 'rgba(0,0,0,0.3)',
- padding: 50,
-
- };
-
- const model = {
- position: 'relative',
- top: 0,
- left: 0,
- display: 'table',
- Width: '100%',
- height: '30%',
- overflow: 'hidden',
- outline: 0,
- backgroundColor: '#fff',
- margin: '0 auto',
- padding: 10,
- maxWidth: 500,
- minHeight: 300,
- };
-
- return (
- <div className="backdrop" style={backdropStyle}>
- <div className="modal" style={model}>
- {this.props.children}
-
- <div className="footer">
- <button className="btn-warning" onClick={this.props.onClose}>
- Close
- </button>
- </div>
- </div>
- </div>
- );
- }
- }
-
- Modal.propTypes = {
- onClose: PropTypes.func.isRequired,
- show: PropTypes.bool,
- children: PropTypes.node
- };
-
- 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,
Lastly, open the index.js file, import necessary library, and write the below code.
- import React from 'react';
- import './App.css';
- import Action from './ModelDemo/Action';
- import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
-
- function App() {
- return (
- <div className="App">
- <Action/>
- </div>
- );
- }
-
- 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.
Add namespace
- using System.Web.Http.Cors;
After that, add the below code inside Register method.
- var cors = new EnableCorsAttribute("*", "*", "*");
- 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.
Now, click on the "Details" button.
Now, take a look at the final operation.
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.