DEV Community

Cover image for Step-by-step Coronavirus Statistics with React and Chart.js Tutorial
Stojanovski Petar
Stojanovski Petar

Posted on

Step-by-step Coronavirus Statistics with React and Chart.js Tutorial

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
2. Tools and Technologies
2.1. Setting up the React environment
2.2. Displaying the Chart
2.2.1. Retrieving Data
2.2.2. Drawing the chart
2.2.3. Language
3. Publishing to Heroku

1. The Idea

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 and the source code:

GitHub logo stojanovskip / coronavirus-statistics

Graphical Representation of the Coronavirus

2. Tools and Technologies

I have previously read and did some data visualization projects, using D3 and Chart.JS, 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

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.

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 - but I will go on explaining it in the following chapters.

2.2. Displaying the Chart

First, we need to fetch the data. This is done be calling the fetch method inside the componendDidMount() function.

2.2.1. Retrieving Data


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

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.


    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

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.

    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

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!

Top comments (4)

Collapse
 
otomer profile image
Tomer Ovadia • Edited

Great achievement while learning new technologies. Since i also created a website of mine, I'm happy to share it here too coronavirus-epidemic.com

Collapse
 
stojanovskip profile image
Stojanovski Petar

Wow! I love the approach. What were the technologies you were using?

Collapse
 
otomer profile image
Tomer Ovadia

Thank you! I actually shared all the details in my website in this link dev.to/otomer/not-just-another-cor...
Feel free to check it :)

Collapse
 
chrisachinga profile image
Chris Achinga

helpful, I will create mine too