Step-by-step Coronavirus Statistics with React and Chart.js Tutorial
Tags: react, chartjs, heroku, tutorial
Published: 2020-03-24 21:26:10

---
title: Step-by-step Coronavirus Statistics with React and Chart.js Tutorial
published: true
description: Tutorial to create a React application with data visualization using ChartJs and publishing it using Heroku.
tags: #react #chartjs #heroku #tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/qfjhcmbutjsvrlghxfwq.png
---
During these difficult times, we need to look at the bright side. So, while staying at home, why don't we try to learn something new. 
That's what I thought and that's what I *did*.
I am sure that everyone, or at least the vast majority of you guys, reading this post heard how *awesome* React is. At least, that was the case with me and after months of postponing I found some time to create my first React App.

## Table of Contents
[1. The Idea](#idea)
[2. Tools and Technologies](#tools)
        [2.1. Setting up the React environment](#setting-react)
        [2.2. Displaying the Chart](#displaying-chart)
        [2.2.1. Retrieving Data](#retrieving-data)
        [2.2.2. Drawing the chart](#draw-chart)
        [2.2.3. Language](#language)
        [3. Publishing to Heroku](#heroku)

## 1. The Idea <a name="idea"></a>

I wanted the project to be "Coronavirus/COVID-19" related, and since I never found a good graphical representation of the current situation, I wanted to make one myself.
This is the [demo](https://mysterious-wave-89332.herokuapp.com/) and the source code: {% github stojanovskip/coronavirus-statistics no-readme %}
## 2. Tools and Technologies <a name="tools"></a>

I have previously read and did some data visualization projects, using [D3](https://d3js.org/) and [Chart.JS](https://www.chartjs.org/), so naturally they were my first options  and Chart.Js being the easier/faster one, I decided to go with it.
As I previously mentioned, the frontend is going to be written using _React_.
At the end, in order everything to be up-to-date with the current data, I started looking for some APIs providing these information. Luckily, there is plenty of data out there I found many useful ones and ended up using this API:

https://rapidapi.com/astsiatsko/api/coronavirus-monitor

Enough chit-chat - let's get to work!

### 2.1. Setting up the React environment <a name="setting-react"></a>

There are plenty of React tutorials out there, so this post is not gonna be a complete React tutorial, but I will go through the most important tasks.

Setting up our first React projects is done in 3 easy steps, using the command line.

> 1. npx create-react-app coronavirus-stats
> 2. cd coronavirus-stats
> 3. npm start


That's it!

Now open your favourite editor and let's begin coding.
In the _src_ directory of the project, there are already some readymade files helping you getting started. The main one we are interested in at the beginning
is the _App.js_ file. There is more than enough at the beginning, so we might begin with removing the generic data - which will leave us with the following code.

```javascript
import React , {Component} from 'react';
import './App.css';
import BarChart from './BarChart'

class App extends Component {
  
  render() {
    return (
      <div className="App">
        <BarChart/>
      </div>
    );
  }
}
export default App;
```

As we can see, the only thing the _render()_ function returns is the reference to our main file *BarChart*. In order this to function properly, we need 
to create the *BarChart.js* file inside the _src_ directory. The _BarChart_ class will handle the fetching of the data and its representation. The class itself
can be found [here](https://github.com/stojanovskip/coronavirus-statistics/blob/master/src/BarChart.js) - but I will go on explaining it in the following chapters.

## 2.2. Displaying the Chart <a name="displaying-chart"></a>
First, we need to fetch the data. This is done be calling the _fetch_ method inside the [componendDidMount()](https://reactjs.org/docs/react-component.html#componentdidmount) function.

### 2.2.1. Retrieving Data <a name="retrieving-data"></a>

```javascript

fetch('https://coronavirus-monitor.p.rapidapi.com/coronavirus/cases_by_country.php',
        {  
            headers: {
              'X-RapidAPI-Host': 'coronavirus-monitor.p.rapidapi.com', 
              'X-RapidAPI-Key': process.env.REACT_APP_API_KEY
            }
        })
            .then(results=>{
            return results.json();
        })
        .then(data => {
			//handle the data
		}		
```
> REMARK: This API, like most of them, needs an API-Key, which basically binds yourself to it. In order to stay safe, for this and any other project in the future,
> you *must* be careful not to include the API-Key as a static value. 
> Instead - put it in a separate file, reference said file to the _.gitignore_ before publishing it and you are good to go.

### 2.2.2. Drawing the Chart <a name="draw-chart"></a>

Once the data is retrieved, we can call our function *drawChartJS()* with all of the _cases_ as a parameter.
Main parts here are the "Ref", the "Canvas", the "Dataset Bars" and the "Chart" itself.

```javascript
	
    chartRef = React.createRef();
	
	...
	
	const myChartRef = this.chartRef.current.getContext("2d");
 
	...
	
	datasetBars = [{
            label: item,
            type: dataType,
            data: itemList,
            backgroundColor: <color>,
            borderColor: <color>,
            fill: <color>,
          },{...}
		  ]
	
	...
	
	  this.myChart = new Chart(myChartRef, {
	  type: "bar",
	  data: {
		  labels: countryList,
		  datasets: datasetBars
	  },
	  options: { 
		  maintainAspectRatio: false,
		  responsive: true
	  }
		});

```

> Remark: In order to stop the flickering of the chart on each update we need to "destroy" the chart before creating a new one with - *this.myChart.destroy();*

### 2.2.3. Language <a name="language"></a>

We are all in this together! So, why not making everyone feel _better_ when reading the data in their own mother tongue. Currently, the application is translated to English and Macedonian, only. 

Since the current state of the application is a one page app, I wanted to make the language support as simple as possible. So, I created a simple JSON array
containing the translations. Therefore, if you would like to contribute by helping me translate it in *your* language, you can do so in the comments, by translating the objects shown below.
```javascript
	phrases: [{"lang":"en","totalCases":"Total cases", "totalDeaths": "Total deaths", "active":"Active","recovered":"Recovered","todayCases":"Today cases","todayDeaths":"Today deaths",  "errorMsg":"Please, input a country.","title":"Coronavirus Statistics","language": "Language","country":"Country"}, {"lang": "mk","language": "Јазик","country":"Држава", "title": "Корона Статистика", "errorMsg":"Ве молиме, внесете држава.", "totalCases":"Вкупно случаи", "totalDeaths":"Вкупно смртни случаи", "active":"Активни","recovered":"Излечени","todayCases":"Денешни случаи","todayDeaths":"Денешни смртни случаи"}]
```
## 3. Publishing to Heroku <a name="heroku"></a>

To publish a demo of the application is the "cherry on top" of the development. What easier way to do so *khm* for free *khm* than Heroku. 
Publishing to Heroku is simple. All you need is to initialize a git repository, provided that you have a Heroku account and have logged in from the command line
(the command being - "heroku login").
The following commands will get your application up and running in no time.
```
	cd coronavirus-stats
	git init
	git add .
	git commit -m "Initial commit"
	heroku create
	git push heroku master
```

## Feedback & Future goals.
I wouldn't stop here. I have more ideas how to improve the application, so I will keep on coding and updating the post as I go.
If you have any suggestions or questions, feel free to reach out. As a beginner in the React framework myself, I would like to know what I can improve or what I am doing wrong, so your
help would be much appreciated.

Thank you!