How to use Material UI (MUI) data grid in Next.js

Cover Image for How to use Material UI (MUI) data grid in Next.js
Ali Bentaleb

In this tutorial, we are going to see how to use Material UI data grid with React based framework like Next.js

Material UI (MUI) data grid

Material UI datagrid is a fast and extendable react data table and react data grid as cited by MUI.

MUI datagrid example

let’s see an example of using the mui datagrid in Next.js

Create pages/datagrid.js and copy the following:

import {DataGrid} from '@mui/x-data-grid';

const columns = [
	{field: 'id', headerName: 'ID', width: 100},
	{
		field: 'userId',
		headerName: 'User ID',
		width: 100,
		align: 'center'
	},
	{
		field: 'title',
		headerName: 'Title',
		width: 400,
		align: 'center'
	},
	{
		field: 'completed',
		headerName: 'Completed',
		width: 80,
		align: 'center'
	}
];

export default function DataGridDemo({rows}) {
	return (
		<div style={{width: '60%', margin: 'auto', marginTop: '2rem'}}>
			<DataGrid
				rows={rows}
				columns={columns}
				pageSize={20}
				autoHeight
				pageSize={20}
				checkboxSelection
				disableSelectionOnClick
			/>
		</div>
	);
}

export const getStaticProps = async () => {
	const rows = await fetch(
		'https://jsonplaceholder.typicode.com/todos/'
	).then((res) => res.json());
	return {
		props: {rows}
	};
};
Now,run _localhost:3000/datagrid_, and tha data grid will pop up

material ui datagrid from API

  • The import is done using import DataGrid from @mui/x-data-grid

  • Column text are centered for each column using prop align:center

  • The datagrid column width is fixed using width:60 , values are in pixel

  • Datagrid also has a boolean property autoHeight to adjust data grid height to content

  • Datagrid prop pageSize let you specify how much rows to display per page, in our example it is configured to 20

  • The mui datagrid is responsive as any mui component, you can try it out on mobile.

  • Rows are populated using typicode API and getStaticProps from Next.js

Material UI datagrid 5 default options

Since version 5 of material ui datagrid, sorting columns and filter columns based on values are activated by default.

Other default options are:

  • columns are sortable
  • columns are resizable
  • columns are not editable
  • columns are pinnable

Color material ui datagrid header

To color material ui datagrid header, use DataGrid prop sx and headerClassName prop for column.

Here is how you can do it:

First, define your sx prop, which takes in a CSS class

 sx={{
          '& .orange': {
            backgroundColor: '#ff943975',
          },

        }}

We have created above a a class called orange, which gives an orange background color.

Second, assign this class to headerClassName prop for the columns

const columns = [
	{field: 'id', headerName: 'ID', width: 90, headerClassName: 'orange'},
	{
		field: 'userId',
		headerName: 'User ID',
		headerClassName: 'orange',

		editable: true,
		resizable: false,
		align: 'center'
	},
	{
		field: 'title',
		headerName: 'Title',
		width: 350,
		editable: true,
		headerClassName: 'orange'
	},
	{
		field: 'completed',
		headerName: 'Completed',
		width: 110,
		editable: true,
		headerClassName: 'orange'
	},
	{
		field: 'fullName',
		headerName: 'Full name',
		description: 'some description',
		sortable: false,
		width: 350,
		valueGetter: (params) =>
			`${params.row.id || ''} ${params.row.title || ''}`,
		headerClassName: 'orange'
	}
];
If you have trouble figuring out how to do it, the full code can be found on bottom of this page.

Color specific cell on mui datagrid

It is also possible to color one of the cells based on cell data, or on its id.

To color cell based on its data, use DataGrid prop _getCellClassName_ , and _sx_ prop to define the CSS class.
_getCellClassName_ prop is a function that takes in cellsParams as a parameter and returns a CSS class _sx_ prop let us define our CSS class to use.
 sx={{
          '& .orange': {
            backgroundColor: '#ff943975',
          },

        }}

         getCellClassName={(params) => {
          return params.row.completed === true ? 'orange' : ''
        }}

Row is colored in Orange if completed column value is true.

Here is the full code

import {DataGrid} from '@mui/x-data-grid';

const columns = [
	{field: 'id', headerName: 'ID', width: 90, headerClassName: 'orange'},
	{
		field: 'userId',
		headerName: 'User ID',
		headerClassName: 'orange',

		editable: true,
		resizable: false,
		align: 'center'
	},
	{
		field: 'title',
		headerName: 'Title',
		width: 350,
		editable: true,
		headerClassName: 'orange'
	},
	{
		field: 'completed',
		headerName: 'Completed',
		width: 110,
		editable: true,
		headerClassName: 'orange'
	},
	{
		field: 'fullName',
		headerName: 'Full name',
		description: 'This column has a value getter and is not sortable.',
		sortable: false,
		width: 350,
		valueGetter: (params) =>
			`${params.row.id || ''} ${params.row.title || ''}`,
		headerClassName: 'orange'
	}
];

export default function DataGridDemo({rows}) {
	return (
		<div style={{width: '80%', margin: 'auto', marginTop: '2rem'}}>
			<DataGrid
				rows={rows}
				columns={columns}
				pageSize={20}
				//rowsPerPageOptions={[5]}
				checkboxSelection
				disableSelectionOnClick
				autoHeight={true}
				sx={{
					'& .orange': {
						backgroundColor: '#ff943975'
					}
				}}
				getCellClassName={(params) => {
					return params.row.completed === true ? 'orange' : '';
				}}
				density="comfortable"
			/>
		</div>
	);
}

export const getStaticProps = async () => {
	const rows = await fetch(
		'https://jsonplaceholder.typicode.com/todos/'
	).then((res) => res.json());
	return {
		props: {rows}
	};
};
Easy guide for MUI autocomplet...How to validate a material UI ...


More interesting articles