Tuesday 26 October 2021

Add Material-UI Table In ReactJS Application

 In this article, we will learn how to use the Material-UI Table in React applications. Material UI is one of the most popular UI frameworks developed by Google. The Material UI library is designed for faster, easier and developer-friendly user interface development. Now Material-UI support in all major browsers and platforms.

 
Prerequisites
  • We should have the basic knowledge of React.js and Web API.
  • Visual Studio and Visual Studio Code IDE should be installed on your system.
  • SQL Server Management Studio
  • Basic knowledge of React strap and HTML
Implementation Steps
  • Create a Database and Table
  • Create Asp.net Web API Project
  • Create React App
  • Install Material-UI
  • Install Axios 

Create a table in the database

 
Open SQL Server Management Studio, create a database named "Employee", and in this database, create a table. Give that table a name like "Employee".
  1. CREATE TABLE [dbo].[Employee](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [Name] [varchar](50) NULL,    
  4.     [Age] [intNULL,    
  5.     [Address] [varchar](50) NULL,    
  6.     [City] [varchar](50) NULL,    
  7.     [ContactNum] [varchar](50) NULL,    
  8.     [Salary] [decimal](18, 0) NULL,    
  9.     [Department] [varchar](50) NULL,    
  10.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED     
  11. (    
  12.     [Id] ASC    
  13. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  14. ON [PRIMARY]    
  15. GO     
Now add a demo data in this table.
 

Create a new Web API project

 
Open Visual Studio and create a new project.
 
Add Material-UI Table In ReactJS Application

Change the name to MatUITable.
 
Add Material-UI Table In ReactJS Application
 
Choose the template as Web API.
 
Add Material-UI Table In ReactJS Application
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
Add Material-UI Table In ReactJS Application
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
Add Material-UI Table In ReactJS Application
 
Select EF Designer from the database and click the "Next" button. 
 
Add Material-UI Table In ReactJS Application
 
Add the connection properties and select the database name on the next page and click OK.
 
Add Material-UI Table In ReactJS Application
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button. 
 
Add Material-UI Table In ReactJS Application
 
Now, our data model is successfully created. 
 
Right-click on the Controllers folder and add a new controller. Name it as "Employee controller" and add the following namespace in the Employee controller.
  1. using MatUITable.Models; 
Now add a method to fetch data from the database.
  1. [HttpGet]  
  2. [Route("employee")]  
  3. public object Getrecord()  
  4. {  
  5.     var emp = DB.Employees.ToList();  
  6.     return emp;  
  7. }  
Complete Hooks controller code
  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 MatUITable.Models;  
  8. namespace MatUITable.Controllers  
  9. {  
  10.   
  11.     [RoutePrefix("Api/Emp")]  
  12.     public class EmployeeController : ApiController  
  13.     {  
  14.         EmployeeEntities DB = new EmployeeEntities();  
  15.         [HttpGet]  
  16.         [Route("employee")]  
  17.         public object Getrecord()  
  18.   
  19.         {  
  20.             var emp = DB.Employees.ToList();  
  21.             return emp;  
  22.         }  
  23.     }  

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 ReactJS project

 
Now let's first create a React application with the following command.
  1. npx create-react-app matform   
Open the newly created project in Visual Studio Code and install Material-UI. 
 

Install Material-UI

 
Now Install Material-UI by using the following command
  1. npm install @material-ui/core --save    
 Now Install the Axios library by using the following command. Learn more about Axios
  1. npm install --save axios   
 Now go to the src folder and add 2 new components; in one component we are going to use classes and in another, we will use Hooks.
  • MatTable.js
  • MatPaginationTable.js
Now open MatTable.js component and import required reference for material UI table
  1. import Table from '@material-ui/core/Table';  
  2. import TableBody from '@material-ui/core/TableBody';  
  3. import TableCell from '@material-ui/core/TableCell';  
  4. import TableContainer from '@material-ui/core/TableContainer';  
  5. import TableHead from '@material-ui/core/TableHead';  
  6. import TableRow from '@material-ui/core/TableRow';  
  7. import Paper from '@material-ui/core/Paper'
 Add the following code in this component.
  1. import React, { Component } from 'react'  
  2. import Table from '@material-ui/core/Table';  
  3. import TableBody from '@material-ui/core/TableBody';  
  4. import TableCell from '@material-ui/core/TableCell';  
  5. import TableContainer from '@material-ui/core/TableContainer';  
  6. import TableHead from '@material-ui/core/TableHead';  
  7. import TableRow from '@material-ui/core/TableRow';  
  8. import Paper from '@material-ui/core/Paper';  
  9. import axios from 'axios';  
  10.   
  11. export class MatTable extends Component {  
  12.   constructor(props) {  
  13.     super(props)  
  14.     this.state = {  
  15.       ProductData: []  
  16.   
  17.     }  
  18.   }  
  19.   componentDidMount() {  
  20.     axios.get('http://localhost:51760/Api/Emp/employee').then(response => {  
  21.       console.log(response.data);  
  22.       this.setState({  
  23.         ProductData: response.data  
  24.       });  
  25.     });  
  26.   }  
  27.   render() {  
  28.     console.log(this.state.ProductData);  
  29.     return (  
  30.       <TableContainer component={Paper}>  
  31.         <Table stickyHeader  aria-label="sticky table">  
  32.           <TableHead>  
  33.             <TableRow>  
  34.               <TableCell>Id</TableCell>  
  35.               <TableCell align="right">Name</TableCell>  
  36.               <TableCell align="right">Age</TableCell>  
  37.               <TableCell align="right">Address</TableCell>  
  38.               <TableCell align="right">City</TableCell>  
  39.               <TableCell align="right">ContactNum</TableCell>  
  40.               <TableCell align="right">Salary</TableCell>  
  41.               <TableCell style={{paddingRight:"60px"}} align="right" >Department</TableCell>  
  42.             </TableRow>  
  43.           </TableHead>  
  44.           <TableBody>  
  45.             {  
  46.               this.state.ProductData.map((p, index) => {  
  47.                 return <TableRow key={index}>  
  48.                   <TableCell component="th" scope="row">  
  49.                     {p.Id}  
  50.                   </TableCell>  
  51.                   <TableCell align="right">{p.Name}</TableCell>  
  52.                   <TableCell align="right">{p.Age}</TableCell>  
  53.                   <TableCell align="right">{p.Address}</TableCell>  
  54.                   <TableCell align="right">{p.City}</TableCell>  
  55.                   <TableCell align="right">{p.ContactNum}</TableCell>  
  56.                   <TableCell align="right">{p.Salary}</TableCell>  
  57.                   <TableCell style={{paddingRight:"114px"}} align="right">{p.Department}</TableCell>  
  58.                 </TableRow>  
  59.               })  
  60.             }  
  61.           </TableBody>  
  62.         </Table>  
  63.       </TableContainer>  
  64.     );  
  65.   }  
  66. }  
  67.   
  68. export default MatTable 
Now run the project by using the following command 'npm start' and check result,
 
Add Material-UI Table In ReactJS Application
Now open MatPaginationTable.js and add the following code to show table with pagination.
  1. import React from 'react';  
  2. import { makeStyles } from '@material-ui/core/styles';  
  3. import Paper from '@material-ui/core/Paper';  
  4. import Table from '@material-ui/core/Table';  
  5. import TableBody from '@material-ui/core/TableBody';  
  6. import TableCell from '@material-ui/core/TableCell';  
  7. import TableContainer from '@material-ui/core/TableContainer';  
  8. import TableHead from '@material-ui/core/TableHead';  
  9. import TablePagination from '@material-ui/core/TablePagination';  
  10. import TableRow from '@material-ui/core/TableRow';  
  11. import axios from 'axios';    
  12. import { useState, useEffect } from 'react'   
  13.   
  14.   
  15. const useStyles = makeStyles({  
  16.   root: {  
  17.     width: '100%',  
  18.   },  
  19.   container: {  
  20.     maxHeight: 440,  
  21.   },  
  22. });  
  23.   
  24. export default function MatPaginationTable() {  
  25.   const classes = useStyles();  
  26.   const [page, setPage] = React.useState(0);  
  27.   const [data, setData] = useState([]);   
  28.   const [rowsPerPage, setRowsPerPage] = React.useState(5);  
  29.   useEffect(() => {    
  30.         const GetData = async () => {    
  31.           const result = await axios('http://localhost:51760/Api/Emp/employee');    
  32.           setData(result.data);    
  33.         }  
  34.         GetData();    
  35.         console.log(data);  
  36. }, []);   
  37.   const handleChangePage = (event, newPage) => {  
  38.     setPage(newPage);  
  39.   };  
  40.   
  41.   const handleChangeRowsPerPage = event => {  
  42.     setRowsPerPage(+event.target.value);  
  43.     setPage(0);  
  44.   };  
  45.   
  46.   return (  
  47.     <Paper className={classes.root}>  
  48.       <TableContainer className={classes.container}>  
  49.         <Table stickyHeader aria-label="sticky table">  
  50.         <TableHead>  
  51.             <TableRow>  
  52.               <TableCell>Id</TableCell>  
  53.               <TableCell align="right">Name</TableCell>  
  54.               <TableCell align="right">Age</TableCell>  
  55.               <TableCell align="right">Address</TableCell>  
  56.               <TableCell align="right">City</TableCell>  
  57.               <TableCell align="right">ContactNum</TableCell>  
  58.               <TableCell align="right">Salary</TableCell>  
  59.               <TableCell align="right">Department</TableCell>  
  60.             </TableRow>  
  61.           </TableHead>  
  62.           <TableBody>  
  63.             {data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map(row => {  
  64.               return (  
  65.            <TableRow >  
  66.                 <TableCell component="th" scope="row">  
  67.                   {row.Id}  
  68.                 </TableCell>  
  69.                 <TableCell align="right">{row.Name}</TableCell>  
  70.                 <TableCell align="right">{row.Age}</TableCell>  
  71.                 <TableCell align="right">{row.Address}</TableCell>  
  72.                 <TableCell align="right">{row.City}</TableCell>  
  73.                 <TableCell align="right">{row.ContactNum}</TableCell>  
  74.                 <TableCell align="right">{row.Salary}</TableCell>  
  75.                 <TableCell align="right">{row.Department}</TableCell>  
  76.               </TableRow>  
  77.                  
  78.               );  
  79.             })}  
  80.           </TableBody>  
  81.         </Table>  
  82.       </TableContainer>  
  83.       <TablePagination  
  84.         rowsPerPageOptions={[5, 10, 15]}  
  85.         component="div"  
  86.         count={data.length}  
  87.         rowsPerPage={rowsPerPage}  
  88.         page={page}  
  89.         onChangePage={handleChangePage}  
  90.         onChangeRowsPerPage={handleChangeRowsPerPage}  
  91.       />  
  92.     </Paper>  
  93.   );  

Add reference of this component in app.js file,
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import MatTable from './MatTable'  
  5. import MatPaginationTable from "./MatPaginationTable";  
  6.     
  7. function App() {  
  8.   return (  
  9.     <div className="App">  
  10.     <MatPaginationTable/>  
  11.     {/* <MatTable/> */}  
  12.     </div>  
  13.   );  
  14. }  
  15.   
  16. export default App; 
Now run the  project
 
Add Material-UI Table In ReactJS Application

Summary

 
In this article, we learned how we install a material UI table and show data in that table using Web API in React applications. Material UI is one of the most popular UI frameworks developed by Google.

No comments:

Post a Comment