How to integrate ReactGrid with Chart.js?
Tags: react, typescript, javascript, datatable
Published: 2021-01-12 08:51:18

[ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts) is a React.js component for displaying and editing data in a spreadsheet-like way. This guide shows you how to integrate it with the well-known pure Javascript library - [Chart.js](https://www.chartjs.org/).

![Audiogram app](https://dev-to-uploads.s3.amazonaws.com/i/64i93s5pbjf05j7dgo9d.png)

## Why ReactGrid?

There are plenty of different data tables available on the Internet, which perform great if you want to display one object per row. 
Each of these objects has to have exactly the same static properties, which are mapped to columns in the table.

[ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts) was designed to be independent of your data model.
It doesn't care about your schema. You can render anything in any cell and thus you are able to display things the way you like it.

Unlike other grid components, [ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts) also performs great on mobile devices or those with a touch capability and provides the same experience as on a desktop.

Before we get started let's list three main tasks:

- displaying the collected data will be achieved with [ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts). To be **reactive** we will re-render the view only when the source data has changed.
  In this example, raw data comes from an audiometer - a device that is used for making hearing tests.
  In a nutshell, audiometer measures multiple hearing difficulties at many frequencies,  and the audiogram is a way of visualizing such disorders.
- visualize the collected data on the line chart using [Chart.js](https://www.chartjs.org/) and its React wrapper,
- add a possibility to enter a new value and rerender the whole view with an updated state.

## Let's code!

**Initialize the project**

Nothing simpler - just type one of the commands below into your terminal to initiate a React app with Typescript support.
'Create React App' will take care of all the necessary stuff.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=project_init %}

**Define useful interfaces and types**

First, we need to declare a few interfaces and types that help us to keep everything in the right place and order.
In this particular example, we know all about the data that we want to process.
A good idea is to 'be as narrow' as possible.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=interfaces.ts %}

**Mark the columns and rows**

Relying on those interfaces now we can introduce `getColumns` function. 
In our app, we got a `Line` column, and after that, we got columns which are related to a particular frequency from 0Hz to 16000Hz.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=columns.ts %}

The next stage is mapping all the rows. We make it in a similar way to previous examples.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=rows.ts %}

**Define the data**

As we defined our data, it's time to define our data that we are working on. `getData` function returns an object whose each key must exist within the `RowsMap` interface. Each key of this object contains an array of `Freq` objects.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=getData.ts %}

**Map the data to ReactGrid**

Now we are ready to generate rows that directly feed into [ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts).  Each row contains the same amount of cells, but all of them can be arbitrarily placed in any order.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=getRows.ts %}

**The main component - `Audiogram`**

It is time to create the main component - `Audiogram` and wrap up already written code. 
As you can see we stored our data inside React `useState` hook. 
[ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts) always expects two props - `columns` (they are constant and don’t change over time) and `rows` (they are calculated every time the `Audiogram` component is rerendered).

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=Audiogram.ts %}

All that's left is to render the component with:

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=index.ts %}

![ReactGrid displaying the data](https://dev-to-uploads.s3.amazonaws.com/i/yge9zdk86yiams491hjr.png)

## Apply changes with the cell editor

There are two things left to do:

1. Add a header row to mark the data (devices and all the frequencies);
2. Add possibility to edit data with [ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts)'s cell editor;

**Adding the header row**

To add it we have to create a short function called `getHeaderRow`. As an argument, it gets a column order (as keys of columns) and returns a row object that contains only a cell of the `header` type. We also added some green background to those cells.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=getHeaderRow.ts %}

![ReactGrid with a header row](https://dev-to-uploads.s3.amazonaws.com/i/kpn2rik57wk9ccej62j6.png)

**Editing frequency values in cell editor**

At this moment [ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts) behaves as a read-only. To change that we updated the `Audiogram` component by adding our handler function called `handleChanges`. We expect that only `NumberCell` will be changed, therefore we marked the `changes` argument as `CellChange<NumberCell>[]`. Our task is to change data on the basis [ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts) has been rendered.

Cell editor opens when it receives double-click action or the Enter key is pressed. 
Then you can type a new value in and then commit the change. If we `console.log(changes)` we get an array of objects as shown below:

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=changes.json %}

To change our raw data we have to find `rowId` where the change takes place. 
Then loop over all frequency samples and apply a new value (`change.newCell.value`) to an appropriate cell or just return without changes.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=AudiogramWithLineChart.ts %}

## Data visualization with Chart.js

[Chart.js](https://www.chartjs.org/) library delivers plenty of components to visualize data, but this time we focus on a single one - `Line` from [`react-chartjs-2`](https://github.com/reactchartjs/react-chartjs-2) that we can use as a React component.

We have to create two functions:
1. `getChartData` - this function should return an object that contains two fields. The `labels` - which is an array of frequency title label and then `datasets` field to provide the `data` field which contains an array of values for each frequency. 
  You can also style your line by setting for example a `backgroundColor` or `pointRadius` for a better experience.

{% gist https://gist.github.com/patryk0493/32c10a2f03059d8153ca300d2f11314f file=getChartData.ts %}

2. `getChartOptions` - here we return an object that is compatible with `ChartOptions` interface. 
  We want to disable legend, set the title, display, and adjust axes.

That's all! The job is done, now you can check the result below.

![Complete app](https://dev-to-uploads.s3.amazonaws.com/i/l0f0raio6h7qdgq951et.png)

{% codesandbox reactgrid-chartjs-audiogram-gtlgr module=src/Audiogram.tsx %}

## Summary

What you learned after completing this guide:
- what is [ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts) and how to do a fully functional app; 
- how you can use it in a reactive way;
- why Typescript is also helpful in a small-scale project to avoid the most common mistakes.

As you see integrating [ReactGrid](https://reactgrid.com/?utm_source=devto&utm_medium=post&utm_campaign=blogcharts) with other libraries like [Chart.js](https://www.chartjs.org/) is not so hard. Of course, you don't need to start a Typescript project and make all data mappings to compose a predictable solution.