DEV Community

Cover image for A Generic table in React with MaterialUI
Jyotirmaya Sahu
Jyotirmaya Sahu

Posted on

A Generic table in React with MaterialUI

Disclaimer
This component is built upon an example on the MaterialUI components section, and hence some part of code may be same. This is just for someone who wants to save some time without trying to figure out all that is done in there.

Introduction

We as react developers must have heard about MaterialUI. It's a fantastic UI library for react (not sure about react native) based on Google's material design.

Now, for dealing with visualizing data in tabular form, it provides a Table component. But configuring it to your needs may look like a pain if you are in a hurry.

A Generic Table component

Here I have a created a DataTable component on the top of the Table component.

DataTable has the following features:

  • Can infer column names if directly array of rows are provided.
  • Can handle sorting at single column level.
  • Supports pagination.
  • Supports custom elements or components inside a cell.
  • Most importantly, we can always customize to our needs.

As, this is a plain React component, you can find the source below, and can improve upon it.

Usage

Basic usage

<DataTable
    columnData={[
        {
            id: 'name',
            name: 'Name',
            enableSort: true,
            align: "center"
        },
        {
            id: 'desc',
            name: 'Description',
            enableSort: true,
            align: "center"
        }
    ]}
    rows={[
       { name: 'First', desc: 'First Item' },
       { name: 'Second', desc: 'Second Item' }
    ]}
/>
Enter fullscreen mode Exit fullscreen mode

The DataTable component takes two parameters, columnData and rows.

The columnData is an array of configuration values for columns, id, name, enableSort_, align.

The rows is the array of objects or we can say it is our data to be displayed in the Table body.

The pagination is same as an example on the MaterialUI components page.

This is open to improvement in discussions and feedback.

Top comments (0)