Add Material-UI Table In ReactJS Application
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."
CREATE TABLE [dbo].[Employee](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Age] [int] NULL,
[Address] [varchar](50) NULL,
[City] [varchar](50) NULL,
[ContactNum] [varchar](50) NULL,
[Salary] [decimal](18, 0) NULL,
[Department] [varchar](50) NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[Id] 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
Now add a demo data in this table.
Create a New Web API Project
Open Visual Studio and create a new project.
Change the name to MatUITable.
Choose the template "Web API."
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> Data.
Click on the "ADO.NET Entity Data Model" option and click "Add."
Select EF Designer from the database and click the "Next" button.
Add the connection properties and select database name on the next page and click OK.
Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button.
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.
xxxxxxxxxx
using MatUITable.Models;
Now add a method to fetch data from the database.
xxxxxxxxxx
[HttpGet]
[Route("employee")]
public object Getrecord()
{
var emp = DB.Employees.ToList();
return emp;
}
Complete Employee Controller Code
xxxxxxxxxx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MatUITable.Models;
namespace MatUITable.Controllers
{
[RoutePrefix("Api/Emp")]
public class EmployeeController : ApiController
{
EmployeeEntities DB = new EmployeeEntities();
[HttpGet]
[Route("employee")]
public object Getrecord()
{
var emp = DB.Employees.ToList();
return emp;
}
}
}
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.
xxxxxxxxxx
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Create ReactJS Project
Now let's first create a React application with the following command.
xxxxxxxxxx
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:
xxxxxxxxxx
npm install -ui/core --save
Now install the Axios library by using the following command. Learn more about Axios here.
xxxxxxxxxx
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.
xxxxxxxxxx
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
Add the following code in this component.
xxxxxxxxxx
import React, { Component } from 'react'
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import axios from 'axios';
export class MatTable extends Component {
constructor(props) {
super(props)
this.state = {
ProductData: []
}
}
componentDidMount() {
axios.get('http://localhost:51760/Api/Emp/employee').then(response => {
console.log(response.data);
this.setState({
ProductData: response.data
});
});
}
render() {
console.log(this.state.ProductData);
return (
<TableContainer component={Paper}>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
<TableCell>Id</TableCell>
<TableCell align="right">Name</TableCell>
<TableCell align="right">Age</TableCell>
<TableCell align="right">Address</TableCell>
<TableCell align="right">City</TableCell>
<TableCell align="right">ContactNum</TableCell>
<TableCell align="right">Salary</TableCell>
<TableCell style={{paddingRight:"60px"}} align="right" >Department</TableCell>
</TableRow>
</TableHead>
<TableBody>
{
this.state.ProductData.map((p, index) => {
return <TableRow key={index}>
<TableCell component="th" scope="row">
{p.Id}
</TableCell>
<TableCell align="right">{p.Name}</TableCell>
<TableCell align="right">{p.Age}</TableCell>
<TableCell align="right">{p.Address}</TableCell>
<TableCell align="right">{p.City}</TableCell>
<TableCell align="right">{p.ContactNum}</TableCell>
<TableCell align="right">{p.Salary}</TableCell>
<TableCell style={{paddingRight:"114px"}} align="right">{p.Department}</TableCell>
</TableRow>
})
}
</TableBody>
</Table>
</TableContainer>
);
}
}
export default MatTable
Now run the project by using the command npm start
and check result.
Now open MatPaginationTable.js and add the following code to show the table with pagination.
xxxxxxxxxx
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import axios from 'axios';
import { useState, useEffect } from 'react'
const useStyles = makeStyles({
root: {
width: '100%',
},
container: {
maxHeight: 440,
},
});
export default function MatPaginationTable() {
const classes = useStyles();
const [page, setPage] = React.useState(0);
const [data, setData] = useState([]);
const [rowsPerPage, setRowsPerPage] = React.useState(5);
useEffect(() => {
const GetData = async () => {
const result = await axios('http://localhost:51760/Api/Emp/employee');
setData(result.data);
}
GetData();
console.log(data);
}, []);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = event => {
setRowsPerPage(+event.target.value);
setPage(0);
};
return (
<Paper className={classes.root}>
<TableContainer className={classes.container}>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
<TableCell>Id</TableCell>
<TableCell align="right">Name</TableCell>
<TableCell align="right">Age</TableCell>
<TableCell align="right">Address</TableCell>
<TableCell align="right">City</TableCell>
<TableCell align="right">ContactNum</TableCell>
<TableCell align="right">Salary</TableCell>
<TableCell align="right">Department</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map(row => {
return (
<TableRow >
<TableCell component="th" scope="row">
{row.Id}
</TableCell>
<TableCell align="right">{row.Name}</TableCell>
<TableCell align="right">{row.Age}</TableCell>
<TableCell align="right">{row.Address}</TableCell>
<TableCell align="right">{row.City}</TableCell>
<TableCell align="right">{row.ContactNum}</TableCell>
<TableCell align="right">{row.Salary}</TableCell>
<TableCell align="right">{row.Department}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
<TablePagination
rowsPerPageOptions={[5, 10, 15]}
component="div"
count={data.length}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
</Paper>
);
}
Add the reference of this component in app.js file.
xxxxxxxxxx
import React from 'react';
import logo from './logo.svg';
import './App.css';
import MatTable from './MatTable'
import MatPaginationTable from "./MatPaginationTable";
function App() {
return (
<div className="App">
<MatPaginationTable/>
{/* <MatTable/> */}
</div>
);
}
export default App;
Now run the project.