In this article, we’ll learn how to integrate material UI data using react. I’ll go through how to install and set up the Data Grid, and consume and integrate a RESTful API. We’ll apply pagination as well as sorting and filtering.
What’s Material UI Data grid
Material UI’s Data Grid is a powerful and flexible data table. It makes it easy for you to display data and perform out-of-the-box functionalities such as editing, sorting, filtering, pagination and more.
According to the Material UI documentation, Data Grid is a
“fast and extendable React data table and React data grid. It’s a feature-rich component available in MIT or Commercial versions“.
The main features of Material Data Grid
There are following main benefits of the material UI data grid.
- Accessibility
- User Interaction
- Data Presentation
Integrate Material Ui data Grid
Let’s implement some of the features of the Data Grid with a public REST API called dummy restapiexample.
How to Install and Setup React and Material UI Data Grid
To create a new React project from the terminal by running the command below:
npx create-react-app data-grid cd data-grid npm start
in the above code, We created a new project called data-grid.
Let’s install two packages which are Material UI and the Data Grid using the command below:
npm install @mui/x-data-grid @mui/material
API Integration and Consumption
Let’s create EmpListing.js
file into src/ folder and fetch data using Fetch API.
import React from 'react' const EmpListing= () => { return ( <div> </div> ) }
Now. We’ll define useState
and useEffect
hooks:
import React, { useState, useEffect } from 'react'
to access our data we will use the useEffect hook and the Fetch API:
useEffect(() => { fetch("https://dummy.restapiexample.com/api/v1/employees") .then((data) => data.json()) .then((data) => setData(data)) }, []) console.log(tableData)
Let’s Integrate useEffect with datagrid component:
import React from 'react' import { DataGrid } from '@mui/x-data-grid' const columns = [ { field: 'id', headerName: 'id' }, { field: 'Name', headerName: 'employee_name', width: 300 }, { field: 'Salary', headerName: 'employee_salary', width: 300 } { field: 'Age', headerName: 'employee_age', width: 300 } ] const EmpListing= () => { const [data, setData] = useState([]) useEffect(() => { fetch("https://dummy.restapiexample.com/api/v1/employees") .then((data) => data.json()) .then((data) => setData(data)) }, []) console.log(tableData); return ( <div style={{ height: 700, width: '100%' }}> <DataGrid rows={tableData} columns={columns} pageSize={12} /> </div> ) } export default EmpListing
Conclusions
We learned about DataGrid in Material UI, React Hooks, REST API consumption. Material UI comes with some features like editing, sorting, filtering, updating, pagination, exports and so on by default.