Using Data Grid Component in MUI X (Material UI) with React

·

7 min read

Using Data Grid Component in MUI X (Material UI) with React

In one of our previous articles, we got to know about the MUI X component library for React. But as we know, MUI X is used for data-rich applications. That's why one of its most popular components is the Material UI Data Grid component.

It can show thousands of data content in multiple ways as you like. Of course, it also comes with essential features to filter, custom styles, etc. To dig more into the feature list in a practical world, either you can use free react templates to build an app or, follow this complete guide as we will create and customize this component in this article. Let's begin.

A Quick Intro of MUI X (Material UI)

  • MUI X is a React UI library that is used to build complex and data-rich applications using a growing list of advanced React components.

This differs from the standard MUI Core library such that the Core offers ready-to-use common components like buttons, cards, toggles, etc but with MUI X you get a limited amount of components that are made for data-heavy apps like the one we are about to discuss and build from scratch.

To create impressive dashboard templates like the "Modernize React MUI Dashboard Theme", you can utilize the MUI data grid component with React. Additionally, you can also take inspiration from this theme and use the MUIX data grid component with React to develop remarkable applications.

You can also check the Demo of Modernize React MUI Dashboard Theme

Material UI Data Grid Component

Material UI Data Grid is superb and one of the most common MUI X components which is extendable and feature-rich with everything you may need in a data-rich table.

Under the hood, it uses React and TypeScript to provide a seamless UX and can manipulate an unlimited amount of data. For real-time updates, it has an API with a focus on accessibility, theming, and fast performance.

Here's what a basic Data Grid table would look like:

Material Ui data grid

As you can see from the above screenshot, the data tables display information in a grid-like format of rows and columns. It's clear and easy to scan, and even with large data users can easily figure out what things are where in the table.

Talking about the features it provides it a lot. But some of them are:

  • Built with and exclusively for React

  • Filtering and multi-filtering

  • Pagination

  • Row & Cell Editing

  • Sorting and multi-sorting

  • Row grouping

  • Tree data

  • Server-side data

  • Localization

In this demo, we will be making a much-improved version of the above table which should look like this:

Material UI data component library

And not only this, of course, we can do actions on the table as shown in the demo below:

There are some exciting actions to be done and code to be written. Let's kick-off!

Installation

There are three basic steps to start using this: installing the package, configuring the columns, and providing the rows and the data will populate!

In our demo, we will be using the MIT-licensed version. To get the actual comparison with the different versions it provides you can check this link.

After you are done setting and running your React application with TypeScript, you can simply run the following command in the terminal window:

npm install @mui/material @mui/x-data-grid @emotion/styled @emotion/react

Yes, we do need the other @mui/material, @emotion/styled and @emotion/react packages for it to work because it's based on the MUI library.

After the installation, we can head on to create our component.

Setup the App.tsx file

Empty out all the code inside your App.tsx. We will be writing the necessary code here.

Export the App() function whose return statement should have just a single

container with two child elements. First, the heading and second, our very own component which we are yet to make. This new component will be under the src/ directory so make sure you import it correctly. With that you should have the following code:

import "./styles.css";
import EmployeeTable from "./employeeTable";
export default function App() {
  return (
    <div className="App">
      <h2>Company Employees</h2>
      <EmployeeTable />
    </div>
  );
}

Create the Data Grid Component

Open up the new component file named employeeTable.tsx and let's make an arrow function named EmployeeTable() to begin with. Inside this, we need to return the JSX for the table. For that, let's create a wrapper which holds the component imported from @mui/x-data-grid giving it the required rows and columns props as:

const EmployeeTable = () => {
  return (
    <div style={{ width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
      />
    </div>
  );
};

Next, let's define our data outside this function. The rows object will take the GridRowsProp type while the columns object will take GridColDef[] definition interface to initialize. Inside each of these, you can add any number of objects inside the array definition with suitable key-value pairs. For us, we will have 3 employee data for rows with a unique id, emp_id, emp_name, emp_profile, and emp_salary as keys and suitable values:

const rows: GridRowsProp = [
  {
    id: 1,
    emp_id: "68319",
    emp_name: "KAYLING",
    emp_profile: "President",
    emp_salary: "60000"
  },
  {
    id: 2,
    emp_id: "68339",
    emp_name: "BLAZE",
    emp_profile: "Manager",
    emp_salary: "47500"
  },
  {
    id: 3,
    emp_id: "68710",
    emp_name: "JONAS",
    emp_profile: "Analyst",
    emp_salary: "30000"
  }
];

As for the columns, we give them the necessary field and headerName properties. It's important as the value of the field will map to their respective rows.

const columns: GridColDef[] = [
  {
    field: "emp_id",
    headerName: "ID",
    width: 100,
    editable: true,
    headerClassName: "header-styles"
  },
  {
    field: "emp_name",
    headerName: "Name",
    width: 100,
    headerClassName: "header-styles"
  },
  {
    field: "emp_profile",
    headerName: "Profile",
    width: 100,
    headerClassName: "header-styles"
  },
  { field: "emp_salary", headerName: "Salary", width: 100 }
];

As you can see, we have also provided optional properties like width, editable, headerClassName. The width simply takes in the amount of width style you need for each column. The editable is a bool where we can manually edit the emp_id by double-clicking the cell. With headerClassName , we can pass on custom styles as written inside the styles.css file:

.header-styles {
  background-color: #3874cb;
  color: white;
  font-weight: bold;
}

The basic table with the data should now populate. Now to make things more interesting, let's pass on some useful attributes to the component:

<DataGrid
  rows={rows}
  columns={columns}
  autoHeight
  initialState={{
    sorting: {
      sortModel: [{ field: "emp_salary", sort: "asc" }],
    },
  }}
  checkboxSelection={true}
  disableSelectionOnClick
  sx={{
    boxShadow: 1,
    "& .MuiDataGrid-cell:hover": {
      color: "primary.main",
    },
  }}
/>;

Here are all the new props:

autoHeight: this is a bool value that when defined automatically adjusts the height of the table according to the data inside it. It's useful when you don't want to manually give a height value to each column.

initialState: this is used as a sort model used to enable sorting in the table. While sorting is enabled by default to the user, we can add manually in which order we want the table data to sort. In this demo, we sort by checking the emp_salary property in ascending order.

checkboxSelection: another bool we can pass to activate the checkbox selection set to select all or some of the rows.

disableSelectionOnClick: useful when you might have some interactive content in the cells and you need to disable the selection of the entire row on click. With this disabled, you can see every time we click a cell, the entire row gets selected.

sx: this is a one-off style prop used in the entire MUI library to specifically style the element. Here we enabled some box-shadow and we changed the color of the cell on hover. And with all that in place, you should have a great working table with the necessary features! Here's the entire code of the component file:

import { DataGrid, GridRowsProp, GridColDef } from "@mui/x-data-grid";
const rows: GridRowsProp = [
  {
    id: 1,
    emp_id: "68319",
    emp_name: "KAYLING",
    emp_profile: "President",
    emp_salary: "60000"
  },
  {
    id: 2,
    emp_id: "68339",
    emp_name: "BLAZE",
    emp_profile: "Manager",
    emp_salary: "47500"
  },
  {
    id: 3,
    emp_id: "68710",
    emp_name: "JONAS",
    emp_profile: "Analyst",
    emp_salary: "30000"
  }
];
const columns: GridColDef[] = [
  {
    field: "emp_id",
    headerName: "ID",
    width: 100,
    editable: true,
    headerClassName: "header-styles"
  },
  {
    field: "emp_name",
    headerName: "Name",
    width: 100,
    headerClassName: "header-styles"
  },
  {
    field: "emp_profile",
    headerName: "Profile",
    width: 100,
    headerClassName: "header-styles"
  },
  { field: "emp_salary", headerName: "Salary", width: 100 }
];
const EmployeeTable = () => {
  return (
    <div style={{ width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
        autoHeight
        initialState={{
          sorting: {
            sortModel: [{ field: "emp_salary", sort: "asc" }]
          }
        }}
        checkboxSelection={true}
        disableSelectionOnClick
        sx={{
          boxShadow: 1,
          "& .MuiDataGrid-cell:hover": {
            color: "primary.main"
          }
        }}
      />
    </div>
  );
};
export default EmployeeTable;

In this article, you got to know about the Material UI Data Grid component in detail. With its powerful features and setup, we finally finished on to make a useful component out of it to use in our React apps. Go ahead and customize your new table with new features!