Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use MUI Data Grid and Save Time

In the fast-paced world of software development, adopting tools and technologies that boost productivity, save time, and maximize efficiency is essential. The core principles of DRY, KISS, and “don’t reinvent the wheel” encourage building on existing solutions rather than starting from scratch.

This is especially relevant in front-end web development, where an explosion of JavaScript libraries and frameworks has created a complex landscape of options for developers. With so many choices, it can be challenging to determine which technologies best suit your needs and will provide the most return on investment.

Tables are a ubiquitous part of most web applications, used to visualize and interact with all kinds of data. However, building custom tables from scratch can be time-consuming, and tricky to get it right cross-browser. This is where leveraging pre-built UI libraries pays dividends.

Material UI is one such library that has emerged as a popular React framework for faster and easier development. It contains a data grid component that handles many complex table features out of the box.

In this comprehensive guide, we’ll explore integrating the Material UI data grid into a React application and populate it with live data from an API. You’ll learn best practices for consuming third-party libraries in React, fetching data from an API, configuring and customizing the grid, and enhancing the overall user experience.

Adopting the Material UI data grid will maximize productivity in building robust, customizable tables in React. By standing on the shoulders of this powerful UI library, you can save significant development time and focus on what makes your application unique.

What is Material UI?

Material UI (MUI) is a widely-used user interface (UI) component library for React that adheres to the principles of Material Design, a design language developed by Google. It offers a collection of reusable and customizable components, enabling developers to create modern and visually appealing user interfaces efficiently.

Material UI Logo

With the release of Material-UI v5, numerous enhancements, performance optimizations, and new functionalities have been introduced, making it a compelling option for front-end development.

MUI was started in 2014 by Hai Nguyen and since then, it has experienced significant growth, boasting 89k+ stars on GitHub, 1.5M+ weekly downloads, with a small bundle size of 93.7kB (Minified + Gzipped).

The chart below ⬇ from NPM trends shows a comparison of the number of downloads of Material UI over the last year.

NPM Trends of MUI

If you use MUI for your project, consider using Purecode.ai to access over 10000+ AI-generated ready-made templates and components to speed up your development process.

Introduction to the Material UI Data Grid

The Material UI Data Grid is a feature-rich React data table and grid, providing functionalities such as editing, sorting, filtering, and pagination out of the box. It offers accessibility features, and keyboard navigation, and is highly extendable with many additional features.

Material UI’s Data Grid is a powerful tool for displaying and interacting with data in React applications.

In this article, we’ll explore the benefits of using the Material UI Data Grid and walk through the process of integrating it with a REST API. We’ll cover installation, API consumption, and how to display API results in the Data Grid. This guide will take you through the process of setting up a React project, rendering the Data Grid component, fetching and displaying data from a REST API, and leveraging the features offered by the Material UI Data Grid.

If you prefer to learn via video tutorial, I have included a YouTube video tutorial for you below:

Why Choose the Material UI Data Grid

MUI comes with many handy features that will allow you to manipulate data in a table easily. Among these features are:

  • Data Presentation: The Data Grid allows data export to CSV format and provides sorting and filtering functionalities.

  • Sorting and multi-sorting: The Data Grid offers intuitive sorting options, allowing you to arrange data in ascending or descending order, even across multiple columns.

  • Pagination: Material UI Data Grid features a built-in pagination mechanism for easy navigation through large data sets, enhancing user accessibility. The grid implements pagination out of the box, so working with large datasets is no problem. Users can comfortably navigate from page to page as needed.

  • Row selection: The ability to select one or multiple rows within the Data Grid facilitates user interaction, aiding in data analysis and user-driven data exploration. Row selection provides another great way for you to dig into the data. Being able to select single or multiple rows at a time enables all sorts of interactions, like deleting rows, comparing values across rows, gathering data, and more.

  • Filtering, multi-filters, and header filters: It provides comprehensive filtering capabilities, from single filters to multi-filters, with header-based filter options, enabling precise data extraction. The grid supports standard filters along with more advanced multi-filters and header filters for really honing in on the exact dataset you need.

  • Built with and exclusively for React ⚛️: Material UI Data Grid is intricately designed and tailored to be a seamless and harmonious extension of React, ensuring optimal compatibility and integration.

Other Reasons

  • Accessibility: The Data Grid offers accessibility features, including keyboard accessibility and density settings. Accessibility is baked in too – keyboard shortcuts, screen reader support, and density settings to optimize the experience.

  • User Interaction: It supports inbuilt row selection, single and multiple row selection, and more.

  • Column groups: The Data Grid allows you to organize and group columns logically, enhancing data presentation and user understanding.

  • High performance 🚀: It delivers lightning-fast data processing and rendering, offering a responsive user experience even with extensive datasets.

  • Row & Cell editing: Last but not least, being able to directly edit cell values and rows enables data manipulation right inside the grid. No need to jump through hoops to update your data! You can seamlessly modify individual cell values or entire rows within the Data Grid, fostering data manipulation and interaction.

MUI Table features

Installation and Setup of React and Material UI Data Grid

To start benefiting from the Material UI Data Grid’s potential in your React application, you must first ensure your development environment is prepared and properly set up. This entails a strategic setup, characterized by the following steps:

  1. Node.js Installation: If you have not already installed Node.js, now is the time. Head to the official Node.js website and install it. Node.js provides you with the Node Package Manager (NPM).

  2. Create React App: With Node.js installed, you can now install Create React App, a tool that expedites the creation of React applications. In your command line interface, run the following command:

    npm i create-react-app -g
    
    
  3. Crafting the React Project: Your adventure begins with creating a new React project. Run the following commands in sequence to get started:

    npx create-react-app mui-data-grid-app
    cd mui-data-grid-app
    npm start
    
    

    You named your project “mui-data-grid-app”, and by running npm start, Your server should launch in your browser at http://localhost:3000/.

  4. Material UI and Data Grid Installation: Our weaponry would be incomplete without the inclusion of Material UI and the Data Grid. With the following command, we equip our project with these essential tools:

    npm install @mui/x-data-grid @mui/material
    
    

You just installed two packages which are Material UI and the Data Grid using the command above ⬆:

API Integration and Consumption

To integrate the API into our React application that was generated using Create-React-App, we first need to create a new folder called components inside the src directory. Within the components folder, we will create a new file called DataTable.

After creating the components folder and DataTable file, our project directory structure should now look like:

  src
      components
          DataTable
  .gitignore
  package-lock.json
  package.json
  README
  1. Create a new folder and file in the src directory, such as components/DataTable.

  2. Implement a functional component in DataTable using React hooks:

    • Use the useState hook to track the state.

    • Use the useEffect hook for handling side effects.

    • Use the Fetch API to fetch data from the REST API.

  3. Import DataTable into App.js to display the results.

Inside the DataTable file, we will build out a functional React component that will contain the logic for consuming the API. Within this component, we can leverage some of React’s built-in features and hooks like useState, useEffect, and useContext to fetch data from the API and manage the state.

For example, we could use the useEffect hook to call the API on the initial component mount and save the data into the state. We could then render this state data to the UI in a tabular grid format to display the API data to the user. The functional component structure allows us to contain all the API logic in one place and reuse the component wherever needed.

Displaying API Results in Material UI Data Grid

1. Import the Data Grid component:

// src/components/DataTable.js ... import { DataGrid } from '@mui/x-data-grid' ... 

2. Configure the columns for the Data Grid:

// src/components/DataTable.js

...

const columns = [
  { field: 'id', headerName: 'ID' },
  { field: 'title', headerName: 'Title', width: 300 },
  { field: 'body', headerName: 'Body', width: 600 }
]

3. Render the Data Grid component with the API data:

// src/components/DataTable.js

...
<div style={{ height: 700, width: '100%' }}>
  <DataGrid
    rows={postData}
    columns={columns}
    pageSize={12}
  />
</div>

...

4. Use the useState hook to persist data from the REST API

Now that we have set up the component structure, the next step is to consume the data from the REST API provided by JSON Placeholder.

To fetch data from an API in React, we need to import the useState and useEffect hooks from React. useState allows us to create state variables and useEffect allows us to run side effects like API calls.

So we will import these two hooks:

// src/components/DataTable.js

...
import React, { useState, useEffect } from 'react';

...

Then we can create a state variable using useState to store the data from the API. We will call it postData:

// src/components/DataTable.js

...
const [postData, setPostData] = useState([]);

...

postData will be used to get the current value of the state, while setPostData will be a function to update the state.

Now in useEffect, we can make the actual API call, store the response in postData using setPostData, and React will re-render our component with the updated data.

// src/components/DataTable.js

...

useEffect(() => {
  fetch("<https://jsonplaceholder.typicode.com/posts>")
    .then((data) => data.json())
    .then((data) => setPostData(data))
}, [])
console.log(postData)

 ...

Data from REST API

This allows us to fetch the data from the API on render and save it to our local component state for easy access in rendering the data table. The useState and useEffect hooks provide a clean way to manage state and side effects when consuming APIs in React.

The complete code is the following:

// src/components/DataTable.js

import React, { useState, useEffect } from "react";
import { DataGrid } from "@mui/x-data-grid";

const DataTable = () => {
  const [postData, setPostData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((data) => data.json())
      .then((data) => setPostData(data));
  }, []);
  console.log(postData);

  const columns = [
    { field: "id", headerName: "ID" },
    { field: "title", headerName: "Title", width: 300 },
    { field: "body", headerName: "Body", width: 600 }
  ];

  return (
    <>
      <div style={{ height: 700, width: "100%" }}>
        <DataGrid rows={postData} columns={columns} pageSize={12} />
      </div>
    </>
  );
};

export default DataTable;

// index.js

import React from "react";
import ReactDOM from "react-dom";
import { Box } from "@material-ui/core";
import "./styles.css";
import DataTable from "../components/DataTable";

function App() {
  return (
    <Box
      component="section"
      sx={{
        p: 6,
        border: "1px dashed grey",
        backgroundColor: "#9966ff",
        backgroundImage: "url(https://play.tailwindcss.com/img/beams.jpg)",
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        display: "flex"
      }}
    >
      <DataTable />
    </Box>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Data-from-REST-API-MUI

Features Material UI Data Grid Provides

The MUI Data Grid includes several features that help with data handling; we’ll look at a few.

Editing

We can make columns editable by adding the editable: true property to the column definition object. This allows inline editing of cell values directly in the grid.

For example:

...
{ field: 'body', headerName: 'Body', width: 600, editable: true },
...

In the above code block, we added editable: true to the body header column.

Sorting

Sorting is enabled by default on column headers. Clicking the header will sort by that column in ascending/descending order.

Filtering

Adding the GridToolbar component enables filtering. We pass this as a component prop:

...

 components={{ Toolbar: GridToolbar }}

...

The complete code for the DataGrid component becomes:

import React, { useState, useEffect } from "react";
import { DataGrid, GridToolbar } from "@mui/x-data-grid";

const DataTable = () => {
  const [postData, setPostData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((data) => data.json())
      .then((data) => setPostData(data));
  }, []);
  console.log(postData);

  const columns = [
    { field: "id", headerName: "ID" },
    { field: "title", headerName: "Title", width: 300 },
    { field: "body", headerName: "Body", width: 600, editable: true }
  ];

  return (
    <>
      <div style={{ height: 700, width: "100%" }}>
        <DataGrid
          components={{ Toolbar: GridToolbar }}
          rows={postData}
          columns={columns}
          pageSize={12}
        />
      </div>
    </>
  );
};

export default DataTable;

This shows the filtering UI in the toolbar. We can then filter by column values.

Data-from-REST-API-Component-MUI

Selection

Row selection can be enabled with the checkboxSelection prop set to true. This displays checkboxes next to each row.

Pagination

Pagination is on by default. We can customize page size, number of rows, page options, etc using the:

  • pagination – enable/disable

  • rowsPerPageOptions – dropdown for rows per page

  • onPageSizeChange – callback when page size changes

  • pageSize – current page size

This gives full control over paginated data.

Overall, these features provide editable, sortable, filterable, and paginated tabular data display in a customizable grid format.

What You Have Learned

In this comprehensive guide, you have gained hands-on experience integrating the powerful Material UI Data Grid into a React application and populating it with live data from a REST API.

We started from the ground up – creating a React project with Create React App, installing the necessary libraries like Material UI and Data Grid, and configuring the overall component structure.

You learned how to fetch external data using the Fetch API and React’s useful hooks like useState and useEffect. Storing the API data in the local state provides the interface to the Data Grid component.

We explored the extensive configuration options for the grid, including defining columns, enabling features like sorting/filtering/pagination, and customizing the overall look and feel.

With the foundations in place, you then saw how to bring it all together: passing the API data into the grid as rows and binding the columns config to display the data.

Finally, you discovered techniques for enhancing the user experience, like search, pagination for large data sets, and even editing data right inside the grid.

Following this comprehensive guide, you now know how to integrate a full-featured, customizable data grid powered by API data into your own React apps. The Material UI component unlocks the ability to visualize, interact with, and manipulate tabular data from any source.

Further Readings

If you enjoyed reading this piece, consider reading other articles from our blogs and also, my recommendations:

By implementing the concepts covered in this article, you will have the ability to design visually appealing and dynamic user interfaces for your React applications using Material UI. Additionally, you will be able to present data in interactive tables.

This YouTube video below ⬇ summarizes everything you have learned so far in this article in just 20 minutes.

If you want to save time and be more efficient in building your own MUI components, you can consider using pre-generated custom MUI components. With over 10,000+ examples to choose from, you can easily find the components you need. Try Purecode.ai now and boost your development speed! 🚀

Happy coding 💻

Emmanuel Uchenna

Emmanuel Uchenna

Emmanuel is an experienced and enthusiastic software developer and technical writer with 4+ proven years of professional experience. He focuses on full-stack web development. He is fluent in React, TypeScript, VueJS, and NodeJS and familiar with industry-standard technologies such as version control, headless CMS, and JAMstack. He is passionate about knowledge sharing.