React Chart.js Integration: Build Professional Charts from Scratch

When presented visually, data gets more exposure (therefore) as data has more influence (therefore) when it’s seen through visuals. By using Chart.js with React, you can convert raw number data into very convincing visual stories. Charts make data, such as sales performance, website traffic, and survey results, easy to read visually at a glance.

As the expectation for interactivity and responsiveness grows, so does the need for responsive and rapid loading of data visualization in a modern web-based application. Chart.js tutorial provides you with everything necessary to create professional charts from scratch. The goal of this course is for you to have a complete understanding of creating line charts, bar charts, pie charts, and doughnut charts at the end; furthermore, you will have an understanding of customizing them for productive use.

What is Chart.js?

Chart.js is one of the most widely used open-source JavaScript libraries for charting. Programmers around the world heavily favor this library for its ease of use, flexibility, and good looks.

The library uses the HTML5 canvas for drawing the charts, making the animation smooth. It comes with a total of eight types ofcharts, which are line, bar, pie, doughnut, radar, polar area, bubble, and scatter. These types ofcharts are customizable in terms of color, font, tool tip, and legend.

Why Choose Chart.js for React Projects?

Why Choose Chart.js for React Projects?

  • Lightweight footprint keeps your bundle size manageable
  • Responsive design adapts automatically to container dimensions
  • Rich documentation speeds up your learning curve
  • Active community provides solutions to common challenges
  • Built-in animations create engaging user experiences without extra code

Setup and Installation

Getting started with react data visualization with chart.js requires just a few terminal commands. Follow these steps to set up your development environment.

To create new project, open your terminal and enter below command. You can use existing one too.

npx create-react-app chart-demo
cd chart-demo

You need two packages for this integration. The first one is chart.js and another is react wrapper for chart.js. Install them using npm:

npm install chart.js react-chartjs-2

Register Chart.js Components

Here’s the full code for your main.js file (or typically App.js in a Create React App project):

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend
);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

This registration step ensures Chart.js loads only the features your application actually needs. Your bundle stays lean and performant.

Creating Different Types of Charts in React

Now comes the prectical part. Let us build four popular chart types with practical examples. Imagine you run an e-commerce store and want to visualize your sales data on a dashboard.

React.js Line Chart Example

Line charts work brilliantly for showing trends over time. Here is how you display monthly revenue for your online store:

import React from 'react';
import { Line } from 'react-chartjs-2';

const RevenueLineChart = () => {
  const data = {
    labels: ['January', 'February', 'March', 'April', 'May', 'June'],
    datasets: [
      {
        label: 'Monthly Revenue (£)',
        data: [12000, 19000, 15000, 25000, 22000, 30000],
        borderColor: 'rgb(75, 192, 192)',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        tension: 0.4
      }
    ]
  };

  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top'
      },
      title: {
        display: true,
        text: 'E-commerce Revenue Trend 2024'
      }
    }
  };

  return <Line data={data} options={options} />;
};

export default RevenueLineChart;

The tension property creates smooth curves between data points. Your stakeholders can instantly spot growth patterns and seasonal dips.

Bar Chart Example in React

Bar charts excel at comparing different categories side by side. Let us visualize sales across product categories:

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

const CategoryBarChart = () => {
  const data = {
    labels: ['Electronics', 'Clothing', 'Home Decor', 'Sports', 'Books'],
    datasets: [
      {
        label: 'Sales Volume',
        data: [450, 320, 280, 190, 240],
        backgroundColor: [
          'rgba(255, 99, 132, 0.7)',
          'rgba(54, 162, 235, 0.7)',
          'rgba(255, 206, 86, 0.7)',
          'rgba(75, 192, 192, 0.7)',
          'rgba(153, 102, 255, 0.7)'
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)'
        ],
        borderWidth: 1
      }
    ]
  };

  const options = {
    responsive: true,
    plugins: {
      legend: {
        display: false
      },
      title: {
        display: true,
        text: 'Sales by Product Category'
      }
    },
    scales: {
      y: {
        beginAtZero: true
      }
    }
  };

  return <Bar data={data} options={options} />;
};

export default CategoryBarChart;

Here, each bar gets its own colour for easy identification. The beginAtZero option ensures fair visual comparison between categories.

Example of Pie Chart in React

Pie charts show how parts contribute to a whole. Perfect for visualizing market share or budget allocation:

import React from 'react';
import { Pie } from 'react-chartjs-2';

const MarketSharePieChart = () => {
  const data = {
    labels: ['Direct Sales', 'Affiliate', 'Social Media', 'Email Marketing', 'Organic Search'],
    datasets: [
      {
        label: 'Traffic Source',
        data: [35, 15, 20, 10, 20],
        backgroundColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56',
          '#4BC0C0',
          '#9966FF'
        ],
        hoverOffset: 4
      }
    ]
  };

  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'right'
      },
      title: {
        display: true,
        text: 'Website Traffic Sources'
      }
    }
  };

  return <Pie data={data} options={options} />;
};

export default MarketSharePieChart;

The hoverOffset property creates a subtle pop-out effect when users hover over segments. This interaction keeps your dashboard engaging.

Doughnut Chart: A Modern Alternative

Doughnut charts function like pie charts but with a hollow centre. Many designers prefer this style for its modern aesthetic. You can even place summary statistics in the centre:

import React from 'react';
import { Doughnut } from 'react-chartjs-2';

const ExpenseDoughnutChart = () => {
  const data = {
    labels: ['Marketing', 'Operations', 'Development', 'Support', 'Miscellaneous'],
    datasets: [
      {
        label: 'Monthly Expenses ($)',
        data: [5000, 8000, 12000, 3000, 2000],
        backgroundColor: [
          '#e74c3c',
          '#3498db',
          '#2ecc71',
          '#f39c12',
          '#9b59b6'
        ],
        borderWidth: 2,
        borderColor: '#ffffff'
      }
    ]
  };

  const options = {
    responsive: true,
    cutout: '60%',
    plugins: {
      legend: {
        position: 'bottom'
      },
      title: {
        display: true,
        text: 'Monthly Expense Breakdown'
      }
    }
  };

  return <Doughnut data={data} options={options} />;
};

export default ExpenseDoughnutChart;

The cutout property controls how large the centre hole appears. A value of 60% creates a balanced doughnut appearance.

Here, we have created components for different types of charts like line chart, bar chart, doughnut chart. Now it’s time to bring this all together and create dashboard. Create a simple dashboard component to display all your charts:

import React from 'react';
import RevenueLineChart from './RevenueLineChart';
import CategoryBarChart from './CategoryBarChart';
import MarketSharePieChart from './MarketSharePieChart';
import ExpenseDoughnutChart from './ExpenseDoughnutChart';

const Dashboard = () => {
  return (
    <div style={{ padding: '20px' }}>
      <h1>Business Analytics Dashboard</h1>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
        <div><RevenueLineChart /></div>
        <div><CategoryBarChart /></div>
        <div><MarketSharePieChart /></div>
        <div><ExpenseDoughnutChart /></div>
      </div>
    </div>
  );
};

export default Dashboard;

It will show all charts into our dashboard component. Add this dashboard component at your preferred screen. For example, replace existing code into App.js with below code:

import React from 'react';
import './App.css';
import Dashboard from './Dashboard';

function App() {
  return <Dashboard />;
}

export default App;

Once you run your server and visit home page, it will show output similar to below image.

ReactJs chart output

Conclusion

With this tutorial you have learned how to create different types of charts using the npm chart.js package for React. You explored how to set up a react project to use the npm chart.js library to create line, bar, pie, and doughnut charts. You’ve learned the essential skills to visualise your data in a professional manner.

Take the time to play around with creating your own datasets and trying different colours and styles for your charts as you continue to improve your knowledge of how to use chart.js with React. As you go through more chart.js/react chart.js tutorials the learning process will be easier and easier.