Latest Ext JS 7.8 is now available. Learn more

React Data Grids – The Complete Guide

September 8, 2022 489 Views
Show

A Data Grid is an essential element for any data-driven application. It renders data in rows and columns and enables users to interact with that data in various ways. The React data grid is a high-performance component that is useful for displaying data in a tabular format. It is extremely fast and capable of loading massive amounts of records in a second. Moreover, React grid layout is a feature-rich component that includes many functionalities, such as data binding, custom sorting, filtering, grouping, and aggregating rows. It also offers much flexibility when it comes to editing and record selection.

React data grid component comes with a design optimized for any resolution. Thus, it works seamlessly on a wide range of devices. Additionally, React data grid comes with an interactive UI and supports touch gestures to provide a great user experience. It also supports various exporting formats, such as PDF, Excel, and CSV.

In this article, we will discuss the steps to create a responsive React [1] grid table easily.

What is a react data grid

How To Install React Data Grid?

You can install the React Data Grid component from the data grid npm by running the following command in the root directory of your project.

npm install  --save react-data-grid

Importing React Data Grid

The following import statement allows you to import the React Data Grid easily.

import ReactDataGrid from 'react-data-grid';

Minimum Configuration

The following code shows how to set the minimum configurations for the data grid you create. The ‘columns’ array describes the columns of the data grid.

<ReactDataGrid

  columns={columns}

  rowGetter={i => rows}

  rowsCount={3} />

Props

The React Data Grid can be configured by passing various Prop values to the component, as shown below. These Props allow you to customize the grid the way you want. While there are many available props, the following three props are essential to render the data grid.

const columns = [

    { key: "id", name: "ID" },

    { key: "name", name: "Name" },

    { key: "amount", name: "Amount" }

  ];

Preparing Your Own Data Grid In React

The React community has developed many React Data Grid components to simplify the creation of sophisticated data grids. These components come packed with all the necessary functionality. Thus, users can use them to create intuitive data grids in minutes.

The following code is a simple react data grid example.

import * as React from "react";

const TableContainer = ({ striped, children }) => (

  <table className={striped ? "table-striped" : ""}>{children}</table>

);

const TableHeader = ({ children }) => <thead>{children}</thead>;

const TableBody = ({ children }) => <tbody>{children}</tbody>;

const TableRow = ({ children }) => <tr>{children}</tr>;

const TableCell = ({ children }) => <td>{children}</td>;

const MyTable = () => (

  <TableContainer striped>

    <TableHeader>

      <TableRow>

        <TableCell>ID</TableCell>

        <TableCell>Name</TableCell>

        <TableCell>Age</TableCell>

      </TableRow>

    </TableHeader>

Data Grid Controls Take Care Of Everything

The biggest advantage of using this data grid component in your React app is the ease of development. You can use the built-in functionality of the component, rather than coding all the way around, to create the data grid from scratch. You can access all these functions using just a few lines of code, and the data grid controls will handle the rest.

Apart from the extensive array of features Data Grid offers, you can also benefit from the support and continuous development.

How A React Data Grid works

Let’s understand the functionality of a Data Grid using the following code block.

import React from "react";

import ReactDataGrid from "react-data-grid";

import { Sparklines, SparklinesLine, SparklinesSpots } from "react-sparklines";

const Sparkline = ({ row }) => (

  <Sparklines

    data={[row.jan, row.feb, row.mar, row.apr, row.may, row.jun]}

    margin={6}

    height={40}

    width={200}

  >

    <SparklinesLine

      style={{ strokeWidth: 3, stroke: "#336aff", fill: "none" }}

    />

    <SparklinesSpots

      size={4}

      style={{ stroke: "#336aff", strokeWidth: 3, fill: "white" }}

    />

  </Sparklines>

);

const columns = [

  { key: "year", name: "Year" },

In the above code, we have defined the columns and rows as objects.

Sometimes we will need to use third-party libraries and plugins for incorporating graphics and charts into grid tables. Here, we have imported and used React Sparklines to display a sparkline. The data set is used to create the sparkline. We have defined the styling for the Sparkline and sparklineSpots using their style property.

Real-Time Data Grid Creation

Sometimes you may need to create Data Grids with live data streaming. Sencha data grid components facilitate live data binding to create more advanced data grids. Moreover, it allows users to visualize the updated data easily by highlighting them in different colors.

Data Binding To The React Data Grid

The first step in binding data to the Data Grid is to create an array of the data items. In the following example, we have created a JSON object that contains ten data items. That data is arranged in columns, including the columns we defined in the previous step.

import  *  as  React  from  'react';

import  *  as  ReactDOM  from  'react-dom';

import { Grid, GridColumn  as  Column } from  '@progress/kendo-react-grid';

import  products  from  './products.json';

const  App = () => {

const [data, setData] = React.useState(products);

return (

  <>

    <Grid  data={data}>

      <Column  field="ProductID" title="ID" width="80px" filterable={false}  />

      <Column field="ProductName"  title="Name"  width="250px"  />

      <Column field="UnitsInStock" title="In stock" filter="numeric" width="100px" cell={InStockCell} />

      <Column field="UnitPrice" title="Price" filter="numeric" width="150px" />

    </Grid>

  </>

);

};

Updating Data Randomly

The variables declared below will help track the state of a specific component.

const [data, setData] = React.useState(products);

const [pausedTimer, setPausedTimer] = React.useState(true);

const [buttonLabel, setButtonLabel] = React.useState('Start');

const changeIntervalRef = React.useRef(null);

The following code block demonstrates a grid table that updates the data at random intervals. Here, we randomly update the field called UnitsInStock with a random number between -4 and 4.

// Randomly selects a set of data items from our data and updates the UnitsInStock field

const  randomizeData = (passedData) => {

let  newData = passedData.slice();

for (

  let  i = Math.round(Math.random() * 10);

  i < newData.length;

  i += Math.round(Math.random() * 10)) {

  updateStock(newData);

}

return  newData;

};

// Randomly adds or removes 0-4 from UnitsInStock and changes the changeType from negative to positive.

const  updateStock = (passedRow) => {

let  oldUnitsInStock = passedRow.UnitsInStock;

let  updatedUnitsInStock = updateStockValue();

updatedUnitsInStock < 0 ? (passedRow.changeType = 'negative') : (passedRow.changeType = 'positive');

passedRow.isChanged = true;

passedRow.UnitsInStock = oldUnitsInStock - updatedUnitsInStock;

};


const  updateStockValue = () => {

  return  Math.floor(Math.random() * 4) * (Math.round(Math.random()) ? 1 : -1);

};

The purpose of the three functionalities defined in the above code is as below.

  • randomizeData – accepts a collection of data and randomly selects values that need to be updated.
  • updateStock – accepts the selected values from randomized data and calculates the amount to add or subtract from UnitsInStock. It also helps identify the updated fields by setting their isChanged property to true.
  • updateStockValue – updateStock function uses this function to add or subtract a value between 0 – 4.

After defining the above functions, we have used the setInterval() and clearInterval() JS functions to randomly update data. We can use them inside two separate functions, as shown below.

// Kicks off when we click on the "Start" button and updates data randomly every second

const  startDataChange = () => {

  clearInterval(changeIntervalRef.current);

  changeIntervalRef.current = setInterval(() => {

  let  newData = randomizeData(data);

  setData(newData);

  }, 1000);

};

// Pauses the data being updated

const  pauseDataChange = () => {

  clearInterval(changeIntervalRef.current);

};

The above startDataChange function will call the randomizeData function each second. It will update values in several rows randomly resulting in an increase or decrease in UnitsInStock.

Updating Cell Styles

Now we have a functional data grid with live data streaming and updated at random intervals. So let’s move on to see how to update the UI of the data grid to reflect the data changes.

In the previous example, we are updating the field “UnitsInStock” with a positive or negative value. So let’s see how to style cells to differentiate these two states, which are positive updates and negative updates.

We can use the green color (#bffdbc3) to highlight a positive update, while using the red color (#ffd1d1) to mark a negative update.

const  InStockCell = (props) => {

const  checkChange = props.dataItem.isChanged || false;

const  field = props.field || '';

const  value = props.dataItem;

if (checkChange === true) {

      let  changeType = props.dataItem.changeType;

  let  cellColors = {};

  changeType === 'positive' ? ((cellColors.color = 'green'), (cellColors.backgroundColor = '#bfdbc3')) : ((cellColors.color = 'red'), (cellColors.backgroundColor = '#ffd1d1'));

      

      return (

        <td

          style={{

            color: cellColors.color,

            background: cellColors.backgroundColor,

          }}

         colSpan={props.colSpan}

         role={'gridcell'}

         aria-colindex={props.ariaColumnIndex}

         aria-selected={props.isSelected}

        >

          {value === null ? '' : props.dataItem.toString()}

        </td>

      );

      } else { // Handles our initial rendering of the cells and can be used to restore cells that have not been updated in a while.

        return (

          <td

            colSpan={props.colSpan}

            role={'gridcell'}

            aria-colindex={props.ariaColumnIndex}

            aria-selected={props.isSelected}

          >

            {value === null ? '' : props.dataItem.toString()}

          </td>

        );

    }

};

While React is a great front-end library, we recommend you to learn the differences of Extjs vs React vs Angular.

Why Choose Sencha For Your React Data Grid?

Sencha is renowned as an excellent app development platform with an extensive collection of components and tools. It offers you the entire set of components to build your React app effortlessly. React Data Grid is one such robust component among them.

Sencha offers an entire solution called GRUI for integrating a React Responsive Grid into your apps. It is an enterprise-level tool with more than a hundred fascinating grid features. Some of these features are infinite scrolling, virtual columns, a sider paging toolbar, column editors, and column drag and drop. Moreover, this GRUI’s React Data Grid offers many benefits to users, such as flexibility in customization, fast integration, and the ability to manage large amounts of data. It is a more effective solution for creating data grids, rather than using the native React Grid Layout that comes with React.

Worried about the performance of the data grid as your data grows? Try ExtJS and understand the difference!

 

Reference

[1] https://reactjs.org/