How to Create a Chart With Multiple Dataset Switching via State in React

Introduction

In the following tutorial, we will cover the basics of how to create a bar chart in React using the React Chart JS 2 NPM package which allows you to produce a multitude of graphs from doughnut to bar-charts and switch between different datasets within a class component.

This can be very useful for creating visualizations for dashboard type applications, allowing you to switch between multiple datasets using State in React.

There is also a video tutorial and source code attached which can help walk you through every step of the process of getting it up and running.

Dependencies
  • React – In this example, I created a project using create-react-app, but you could create this using any configuration of React.
  • React Chart JS 2

Step 1: Install React Chart JS 2 and Create a Class Component for a Bar Chart

First, we need to install React Chart JS 2 and set up a basic class component containing our chart, as well as associated UI.

Assuming you have your React project initialized (look to this tutorial for a guide to setting up a React project using create-react-app if you need help with this) you first need to run the following command in the directory containing your package.json in your terminal:

npm install --save react-chartjs-2 chart.js

With that, you have the package installed for handling the chart rendering.

Next let’s create the base of our class component which will contain the new bar chart and which we will import into our app (wherever you want really, but if you are following my example, in app.js generated by create React app).

To create a new .JS file as below called BarChart.js (In my example I have it in a folder called components):

import React,{Component} from 'react';
// WE ARE USING THE BAR FROM THE PACKAE SO WE IMPORT THIS IN TO BE READY
import {Bar} from 'react-chartjs-2';

class BarChart extends Component
{
  constructor() {
    super();
    this.state = {
     //This is our initial state for the bar chart data, which for now is an empty array
      barChartData: []
    }
  }

 
  render() {
    return (
        <div>
               // WE WILL ADD OUR OUR CHART IN HERE
        </div>
  )
  }
}

export default (BarChart);

Step 2: Let’s Add Some Data to Our Chart

Ok, so far so good (well hopefully)! Next, let’s add a dataset to our chart so that it displays something! To do that, we will use test data in this example.

Three main things to bear in mind here:

  • We create a new method called change0() – this loads our initial dataset and sets the state to the initial data we want to represent (in the example numerical dummy data for 3 months). The reason we call it change0() will become apparent in a few more steps.
  • We set the State using the SetState() method which is how to set State in React – this assigns the value we pass to the state barChartData in React.
  • We call the method change0() within the componentDidMount() lifecycle method – this lifecycle method is a React method which essentially means ‘do these things once the component has mounted‘ – so we want to load our initial data into the State.

NOTE: In a real-world example you would likely get this data from props or State values, but the important thing is how we structure it, for now.

import React,{Component} from 'react';
//Make sure not to forget toimport Bar from the package (This is important it won't work without this step)
import {Bar} from 'react-chartjs-2';

class BarChart extends Component
{
  constructor() {
    super();
    this.state = {
      barChartData: []
    }
  }

  componentDidMount() {
    this.change0();
    }

  change0(){
    this.setState({
      barChartData:{
        labels: ['January', 'February', 'March',],
        datasets: [
          {
            label: '3 Months',
            backgroundColor: 'rgba(255,99,132,0.2)',
            borderColor: 'rgba(255,99,132,1)',
            borderWidth: 1,
            hoverBackgroundColor: 'rgba(255,99,132,0.4)',
            hoverBorderColor: 'rgba(255,99,132,1)',
            data: [65, 59, 80]
          }
        ]
      }
    })
  }

  render() {
    return (
        <div>
          <Bar data={this.state.barChartData}  />
        </div>
  )
  }
}

export default (BarChart);

bada bing bada bosh this should now display some data in a bar chart format! But we also need to display this component somewhere, and here is how you (as an example) do this.

import React from 'react';
import './App.css';
// OUR NEW COMPONENT IMPORTED 
import BarChart from "./components/BarChart";

function App() {
  return (
    <div className="App">
// REF TO OUR FRESHLY CREATED CLASS COMPONENT 
     <BarChart/>
    </div>
  );
}

export default App;

Step 3: Going Further – Switching Between Multiple Datasets

So that’s all well and good, but what if we wanted to switch between multiple data-views on one chart?

To solve this we’ll create 2 more methods for loading data, and add some buttons with event bindings to switch between them.

import React,{Component} from 'react';
import {Bar} from 'react-chartjs-2';

class BarChart extends Component
{
  constructor() {
    super();
    this.state = {
      barChartData: []
    }
//EVENT BINDINGS FOR ONCLICK EVENTS ON BUTTONS
    this.change0 = this.change0.bind(this);
    this.change1 = this.change1.bind(this);
    this.change2 = this.change2.bind(this);
  }

  componentDidMount() {
    this.change0();
    }


  change0(){
    this.setState({
      barChartData:{
        labels: ['January', 'February', 'March',],
        datasets: [
          {
            label: '3 Months',
            backgroundColor: 'rgba(255,99,132,0.2)',
            borderColor: 'rgba(255,99,132,1)',
            borderWidth: 1,
            hoverBackgroundColor: 'rgba(255,99,132,0.4)',
            hoverBorderColor: 'rgba(255,99,132,1)',
            data: [65, 59, 80]
          }
        ]
      }
    })
  }
    //OUR TWO NEW METHODS FOR  UPDATING THE STATE barChartData BASED ON EVENTS ON CLICK 
    change1(){
      this.setState({
        barChartData:{
          labels: ['January', 'February', 'March','April','May','June'],
          datasets: [
            {
              label: '6 Months',
              backgroundColor: 'rgba(255,99,132,0.2)',
              borderColor: 'rgba(255,99,132,1)',
              borderWidth: 1,
              hoverBackgroundColor: 'rgba(255,99,132,0.4)',
              hoverBorderColor: 'rgba(255,99,132,1)',
              data: [49, 22, 23,65,43,21]
            }
          ]
        }
      })
    }

  change2(){
    this.setState({
      barChartData:{
        labels: ['January', 'February', 'March','April','May','June', 'July', 'Aug', 'Sept','Oct', 'Nov', 'Dec'],
        datasets: [
          {
            label: 'One Year',
            backgroundColor: 'rgba(255,99,132,0.2)',
            borderColor: 'rgba(255,99,132,1)',
            borderWidth: 1,
            hoverBackgroundColor: 'rgba(255,99,132,0.4)',
            hoverBorderColor: 'rgba(255,99,132,1)',
            data: [49, 22, 23,65,43,21,56,57, 100,23,43,21,]
          }
        ]
      }
    })
  }

  render() {
    return (
        <div>
          <Bar data={this.state.barChartData}  />
          //OUR ON CLICK EVENTS ARE DEFINED HERE - ALLOWING THE USER TO SWITCH BETWEEN VIEWS AND UPDATE THE STATE OF BarChartData on the fly
          <button onClick={this.change0}>Change to 3 months</button>
          <button onClick={this.change1}>Change to 6 months</button>
          <button onClick={this.change2}>Change to 1 year</button>
          {/*<button onClick={this.change2}></button>*/}
        </div>
  )
  }
}

export default (BarChart);

And now we have a simple bar chart component that allows switching of datasets.

YouTube Video to this Tutorial:

3
1

Related Posts