How to create data tables using Material-Table?

How to create data tables using Material-Table?
Material-Table library to data table components for react app

Introduction

Built using the popular library, Material UI, Material-table is an easy way to create data tables in react application. In this article, we will learn to get started with Material-table by building a simple table for a college with student details.

Material-table is one of the best and feature rich component library which enables custom layout of table, styling as one prefer, supports sorting, searching by default and performative pagination feature, filtering columns, adding, deleting and updating the row data in the table, export or upload data and other features.

As it is built using the Material UI library, Material-table can leverage Material UI’s icons, layouts, components. If you are already using Material UI in your React app, then Material-table is best suited for presenting data in table format.

Before we begin with the initial setup of Material-table, it is worth noting that the minimum version of React should be 16.8.5 since the Material-table version 1.36.1 for drag and drop functionalities using react hook. If not for this feature, you can proceed with the version 1.36.0 of Material-table

Installation

Start by setting up the project by using the create-react-app boiler code. Use the below command to create the React app

For NPM use:

npx create-react-app myapp

For Yarn use:

yarn create react-app myapp

After the above command as executed, run the below command to get to the root folder of the project.

cd myapp

Executing npm start or yarn start should launch the app in the localhost:3000, if everything goes well.

Next, getting the Material-table in the React app.

If you are using NPM, then use the below command to install the Material-table package:

npm install material-table @material-ui/core --save

You can install the Material-table package with yarn package manager by using the below command:

yarn add material-table @material-ui/core

Both commands do the same work, it would install Material-UI and Material-table packages.

Now you can simply import the Material table in any component of your React project as below:

import MaterialTable from "material-table";

Create a Material-Table

In your ‘src’ folder of React project, create a folder ‘components’ and a JS file with name ‘Students’.

Let’s create a simple table for a college with details of students. We will begin with creating a component named Students, which returns the Material-table. It would look like below,

const Students = () ⇒ {
	return (
		<MaterialeTable/>)
}
export default Students

We can add on to the Material Table component to have different feature available on the table, as we move forward. One can also pass data to the function component and consume it in the Material-Table as necessary.

Start by giving a title to our table, with title prop of Material-table, let’s also provide the columns like name, age, fee of students using the column props.

Add data to the Material-table to populate the row in the table. Our code would look something like this now.

import MaterialTable from "material-table";
const Students = () => {
	return (
		<MaterialTable
			title="Students information"
			columns={[
            { title: "Name", field: "name" },
            { title: "Age", field: "age" },
            { title: "Fee", field: "fee" }
            ]}
			data={[{name: "Salman", age: 25, fee: 500}]}
		/>);
};
export default Students;

Table view as below:

Material Table initial render

As you can find in the above screenshot, the Search field and pagination at the bottom is provided by default. We can disable them if we want to by defining in the Material-table props ‘Options’.

Before we do that, let’s fix the icons which are not showing up, instead text like ‘search’, ‘first’, ‘last’ are seen.

To fix this, we can simply include the icons from Material UI library. First import the icons from Material UI and then provide the icons to Material-table using the ‘Icons’ prop.

The recommended way of importing the icons and using them is as follows:

import { forwardRef } from 'react';

import AddBox from '@material-ui/icons/AddBox';
import ArrowDownward from '@material-ui/icons/ArrowDownward';
import Check from '@material-ui/icons/Check';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import FirstPage from '@material-ui/icons/FirstPage';
import LastPage from '@material-ui/icons/LastPage';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';

const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />),
    ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
  };

<MaterialTable
  icons={tableIcons}
  ...
/>

After doing the above steps, our table should have icons. Remember, we did not have to do any CSS to arrive at the simple layout. However, you can customize the table as you prefer.

Material Table with Material UI icons

Now, we would add a button to add a new row to our table. For that, we can simply include the actions prop to the Material-table component and editable prop for updating the table view to show the newly added value.

<MaterialTable
	actions={[
        {
          icon: tableIcons.Add,
          tooltip: "Add a student",
          isFreeAction: true,
          onClick: (event, rowData) => alert("You want to add a new row"),
        },
      ]}
	editable={
				onRowAdd: newData =>
            new Promise((resolve, reject) => {
                setTimeout(() => {
                    /* setData([...data, newData]); */

                    resolve();
                }, 1000);
            }),
			}
/>

The same can be done for achieving the deletion, update operations on the row, just by the editable prop.

You can also override a component in the Material-table with your own custom component.

<MaterialTable
	// other props
    components={{      
    Toolbar: props => (
    <div style={{ backgroundColor: 'cyan' }}>
    	<MTableToolbar {...props} />
    </div>)
    }}
/>

Our updated table with the Add button and custom toolbar component would looks like this:

Material Table with custom component

For reference, You can find the code for the above table we have build at the codesandbox link here: https://codesandbox.io/s/strange-babycat-z074g8?file=/src/components/Students.jsx

Conclusion:

We have only touch-based upon the simpler features of Material-table, but this should be good enough for getting started.

Material-table provides us many more features as we discussed earlier, adding to those, it also provides us remote data fetch to table, grouping, localization, selection, search, sort, validation, custom render of the columns.

The official docs are briefly written with code examples and demo for each feature. Material-table components jells well with the Material UI, which makes Material-table the go-to library for the creating data tables with high customizability. Adding to that, it is actively maintained on GitHub.

But the noticeable downside would be that this library takes up much space in the project.

Other alternative libraries include, React table, MUI data tables, which are either not component based or not full of features but light-weighted compared to Material-table.

Resources

Material-table official docs - Material-table

A thorough discussed video from YouTube by codenemy - Learn Material Table with React in 1Hr


Subscribe to the newsletter for more insightful info on web development like this and other technical information, tips and tricks.

Read more