DEV Community

Cover image for Data Visualisation in React Using Chart.js
Rifky Alfarez
Rifky Alfarez

Posted on

Data Visualisation in React Using Chart.js

Creating interactive and visually appealing charts is an essential skill for developers working on modern web applications. Chart.js, a popular JavaScript library for data visualization, provides a simple yet powerful way to create various types of charts, such as bar, line, pie, and more. When combined with React, a widely-used JavaScript library for building user interfaces, it becomes an efficient tool for crafting dynamic and responsive visualizations. In this article, we’ll explore how to integrate Chart.js into a React project and create stunning charts step by step.

Install Dependencies

  • Install react using vite
npm create vite@latest
Enter fullscreen mode Exit fullscreen mode

at the prompt in the terminal enter the project name, then select react, and adjust whether to use javascript or typescript according to your preference.

  • Install chart.js and react chart js 2
npm i chart.js react-chartjs-2
Enter fullscreen mode Exit fullscreen mode

The react-chartjs-2 library acts as a React wrapper for the Chart.js library. It simplifies the process of integrating Chart.js into React applications by providing pre-built React components for various types of charts (e.g., Line, Bar, Pie).

Folder Structure

Folder Structure

Delete unnecessary files and folders and create a components folder.

Create Chart Components

Inside the components folder, create a file to create the chart.

Chart Component

Bar Chart

  • Import the required libraries At this stage you can use 2 ways, lazy way and tree-shakable way.

Lazy way

import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';
Enter fullscreen mode Exit fullscreen mode

Tree-shakable way

import { Chart } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);
Enter fullscreen mode Exit fullscreen mode

Both approaches to integrating Chart.js with React (Lazy way and Tree-shakable way) have their own advantages and trade-offs.

The Lazy way, which uses import 'chart.js/auto', is quick and simple to implement. It automatically registers all necessary Chart.js components, making it an excellent choice for small projects or quick prototypes. However, this approach can result in larger bundle sizes because it imports and registers all Chart.js components, even those you may not use in your application.

Lazy way

On the other hand, the Tree-shakable way provides better optimization by allowing you to import and register only the Chart.js components you need. This leads to smaller bundle sizes, improving application performance, especially in larger or production-grade projects. However, it requires more setup and manual management of registered components, which might be more complex or tedious for beginners or simple use cases.

Tree shake

In conclusion, the Lazy way is ideal for simplicity and speed in development, while the Tree-shakable way is preferred for production environments where performance and bundle size are critical.

But in this article we will use the lazy way for simplicity.

  • Create Chart
import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';

export default function BarChart() {
  const options = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Steps taken per day',
      },
    },
  };

  const data = {
    labels: [
      'Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
    ],
    datasets: [
      {
        label: 'John',
        data: [10200, 8212, 9435, 10032, 8756, 10324, 9021],
        backgroundColor: '#ef4444',
      },
      {
        label: 'Jane',
        data: [8010, 9432, 9401, 8790, 10431, 9110, 8833],
        backgroundColor: '#3b82f6',
      },
    ],
  };

  return (
    <div>
      <Chart type="bar" data={data} options={options} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The Chart component in react-chartjs-2 requires three main properties: type, data, and options.

type: Specifies the type of chart to render, such as bar, line, pie, and more. This determines the overall appearance and structure of the chart.

data: Contains the labels and datasets that define what the chart displays. For example, in a bar chart, data includes the categories on the x-axis and the values for each dataset.

options: Configures additional settings for the chart, such as responsiveness, plugins (e.g., title and tooltip), and layout adjustments. This property allows you to customize the chart's behavior and appearance.

These three properties work together to create a fully functional and interactive chart in React.

Bar Chart

Doughnut Chart

import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';

export default function DoughnutChart() {
  const options = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Gender of students in a class',
      },
    },
  };

  const data = {
    labels: ['Man', 'Woman', 'Other'],
    datasets: [
      {
        label: 'Total',
        data: [45, 50, 5],
        backgroundColor: ['#ef4444', '#3b82f6', '#22c55e'],
      },
    ],
  };

  return (
    <div className="h-[400px] flex items-center justify-center">
      <Chart type="doughnut" data={data} options={options} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Line Chart

import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';

export default function LineChart() {
  const options = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Steps taken per day',
      },
    },
  };

  const data = {
    labels: [
      'Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
    ],
    datasets: [
      {
        label: 'John',
        data: [10200, 8212, 9435, 10032, 8756, 10324, 9021],
        fill: true,
        backgroundColor: '#ef444450',
        borderColor: '#ef4444',
        tension: 0.5,
      },
      {
        label: 'Jane',
        data: [8010, 9432, 9401, 8790, 10431, 9110, 8833],
        fill: true,
        backgroundColor: '#3b82f650',
        borderColor: '#3b82f6',
        tension: 0.5,
      },
    ],
  };

  return (
    <div>
      <Chart type="line" data={data} options={options} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Pie Chart

import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';

export default function PieChart() {
  const options = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Gender of students in a class',
      },
    },
  };

  const data = {
    labels: ['Man', 'Woman', 'Other'],
    datasets: [
      {
        label: 'Total',
        data: [45, 50, 5],
        backgroundColor: ['#ef4444', '#3b82f6', '#22c55e'],
      },
    ],
  };

  return (
    <div className="h-[400px] flex items-center justify-center">
      <Chart type="pie" data={data} options={options} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Preview

Refactoring

You can also move the data into a new file and display the data using mapping.

//data.ts

export const stepsData = [
  {
    name: 'John',
    steps: [
      {
        day: 'Sunday',
        value: 10200,
      },
      {
        day: 'Monday',
        value: 8212,
      },
      {
        day: 'Tuesday',
        value: 9435,
      },
      {
        day: 'Wednesday',
        value: 10032,
      },
      {
        day: 'Thursday',
        value: 8756,
      },
      {
        day: 'Friday',
        value: 10324,
      },
      {
        day: 'Saturday',
        value: 9021,
      },
    ],
  },
  {
    name: 'Jane',
    steps: [
      {
        day: 'Sunday',
        value: 8010,
      },
      {
        day: 'Monday',
        value: 9432,
      },
      {
        day: 'Tuesday',
        value: 9401,
      },
      {
        day: 'Wednesday',
        value: 8790,
      },
      {
        day: 'Thursday',
        value: 10431,
      },
      {
        day: 'Friday',
        value: 9110,
      },
      {
        day: 'Saturday',
        value: 8833,
      },
    ],
  },
];
Enter fullscreen mode Exit fullscreen mode
import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';
import { stepsData } from '../utils/data';

export default function LineChart() {
  const options = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Steps taken per day',
      },
    },
  };

  const labels = stepsData[0]?.steps.map((step) => step.day);

  const datasets = stepsData.map((person) => ({
    label: person.name,
    data: person.steps.map((step) => step.value),
    fill: true,
    tension: 0.5,
  }));

  const data = {
    labels,
    datasets,
  };

  return (
    <div>
      <Chart type="line" data={data} options={options} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we explored how to integrate Chart.js with React to create visually engaging and interactive charts, including Bar, Doughnut, Line, and Pie charts. I hope this guide has helped you get started with data visualization in React. For further exploration and to access the full code, feel free to check out the project repository at the link below.

If you’d like to see more of my work or learn more about me, visit my portfolio at www.rifkyalfarez.my.id.

Thank you for reading, and happy coding!

GitHub Repository Link: https://github.com/rfkyalf/react-chartjs

References:
https://www.chartjs.org/docs/latest/
https://react-chartjs-2-two.vercel.app/

Top comments (0)