DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java Module Benefits With Example
  • Providing Enum Consistency Between Application and Data
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Ultra-Fast Microservices: When MicroStream Meets Helidon

Trending

  • Build Self-Managing Data Pipelines With an LLM Agent
  • Building an Image Classification Pipeline With Apache Camel and Deep Java Library (DJL)
  • A Scalable Framework for Enterprise Salesforce Optimization: Turning Outcomes Into an Operating System
  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  1. DZone
  2. Data Engineering
  3. Databases
  4. Add Material-UI Table In ReactJS Application

Add Material-UI Table In ReactJS Application

Take a look at how you can use React.js to make a Material-UI in React applications.

By 
Sanwar Ranwa user avatar
Sanwar Ranwa
DZone Core CORE ·
Updated May. 18, 22 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
27.6K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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 is supported 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 

You may also enjoy: How to Learn React.js, Part 1: The React Road Map for Modern Web Developers 

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."

Java
 




x
15


 
1
CREATE TABLE [dbo].[Employee](    
2
    [Id] [int] IDENTITY(1,1) NOT NULL,    
3
    [Name] [varchar](50) NULL,    
4
    [Age] [int] NULL,    
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 = ON) ON [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.

Create new project

Create new project


Change the name to MatUITable.

Changing the name

Changing the name


Choose the template "Web API."

Choosing a template

Choosing a template


Right-click the Models folder from Solution Explorer and go to Add >> New Item >> Data.

Add data

Add data


Click on the "ADO.NET Entity Data Model" option and click "Add."

Add ADO.NET Entity Data Model

Add ADO.NET Entity Data Model


Select EF Designer from the database and click the "Next" button. 

Select EF Designer

Select EF Designer


Add the connection properties and select database name on the next page and click OK.

Add connections properties

Add connections properties


Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button.

Finished

Finished


Now, our data model is successfully created. 

Right-click on the Controllers folder and add a new controller. Name it "Employee controller" and add the following namespace in the Employee controller.

Java
 




xxxxxxxxxx
1


 
1
using MatUITable.Models; 


Now add a method to fetch data from the database.

Java
 




xxxxxxxxxx
1


 
1
[HttpGet]  
2
[Route("employee")]  
3
public object Getrecord()  
4
{  
5
    var emp = DB.Employees.ToList();  
6
    return emp;  
7
} 


Complete Employee Controller Code

Java
 




xxxxxxxxxx
1
24


 
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
    }  
24
} 


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.

Java
 




xxxxxxxxxx
1


 
1
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");        
2
config.EnableCors(cors); 


Create ReactJS Project

Now let's first create a React application with the following command.

Java
 




xxxxxxxxxx
1


 
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:

Java
 




xxxxxxxxxx
1


 
1
npm install @material-ui/core --save


 Now install the Axios library by using the following command. Learn more about Axios here.

Java
 




xxxxxxxxxx
1


 
1
npm install --save axios  


Now go to the src folder and add two 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.

JavaScript
 




xxxxxxxxxx
1


 
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.

JavaScript
 




xxxxxxxxxx
1
68


 
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 command  npm start  and check result.

Running the project

Running the project


Now open MatPaginationTable.js and add the following code to show the table with pagination.

JavaScript
 




xxxxxxxxxx
1
94


 
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
  );  
94
} 


Add the reference of this component in app.js file.

JavaScript
 




xxxxxxxxxx
1
16


 
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.

Finished the project

Finished the project


Database application Web API Visual Studio Code Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Java Module Benefits With Example
  • Providing Enum Consistency Between Application and Data
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Ultra-Fast Microservices: When MicroStream Meets Helidon

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook