DEV Community

Cover image for Chart.js implementation with Lightning Web Components💻👩‍💻
Nayan Kaslikar
Nayan Kaslikar

Posted on

Chart.js implementation with Lightning Web Components💻👩‍💻

In today's data-driven world, effective visualization is key to understanding complex information and making informed decisions. Salesforce Lightning Web Components (LWC) provide a powerful framework for building dynamic user interfaces within the Salesforce ecosystem. When paired with Chart.js, a versatile JavaScript library for creating interactive charts, LWC becomes even more potent, enabling developers to create visually compelling data visualizations seamlessly integrated into their applications.

In this blog post, we'll walk through the process of integrating Chart.js with Lightning Web Components, unlocking a world of possibilities for data visualization within Salesforce.

Step 1: Installing Chart.js 🪛

To kickstart our integration, we need to install/download the Chart.js library into our LWC project. Use the below link to download Chart.js.

cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js

Now add this file in static resource for further use.

Step 2: Importing Chart.js 🎯

Once Chart.js is installed, we import it into our Lightning Web Component.

import { loadScript } from 'lightning/platformResourceLoader';
import ChartJs from '@salesforce/resourceUrl/ChartJs'; 
Enter fullscreen mode Exit fullscreen mode

Step 3: Loading Chart.js Script 🚀

We then load the Chart.js script within the connectedCallback() lifecycle hook of our LWC component.

@track isChartJsInitialized = false;
    renderedCallback() {
        if (this.isChartJsInitialized) {
            return;
        }
        this.isChartJsInitialized = true;
        Promise.all([
            loadScript(this, ChartJs)
        ])
        .then(() => {
            // Chart.js library loaded
            this.initializePieChart();
        })
        .catch(error => {
            console.log('Error loading Chart.js');
            console.error(error);
        });
    }
Enter fullscreen mode Exit fullscreen mode

Step 4: Creating the Canvas Element 🖼️

In the HTML template of our LWC component, we create a canvas element to render the chart.

<div>
        <canvas id="pieChart" width="400" height="400"></canvas>
 </div>
Enter fullscreen mode Exit fullscreen mode

Step 5: Initializing the Chart 🪄

Within the JavaScript file of our LWC component, we initialize and render the chart using Chart.js.

import { LightningElement, track } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import ChartJs from '@salesforce/resourceUrl/ChartJs'; 
export default class PieChart extends LightningElement {
    @track isChartJsInitialized = false;
    renderedCallback() {
        if (this.isChartJsInitialized) {
            return;
        }
        this.isChartJsInitialized = true;
        Promise.all([
            loadScript(this, ChartJs)
        ])
        .then(() => {
            // Chart.js library loaded
            this.initializePieChart();
        })
        .catch(error => {
            console.log('Error loading Chart.js');
            console.error(error);
        });
    }
    initializePieChart() {
        const ctx = this.template.querySelector('canvas').getContext('2d');
        new window.Chart(ctx, {
            type: 'pie',
            data: {

                labels: ['Website Forms', 'Social Media ', 'Email Marketing Campaigns', 'Referrals', 'Partner Channels', 'Networking'],
            datasets: [{

                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.5)',
                    'rgba(54, 162, 235, 0.5)',
                    'rgba(255, 206, 86, 0.5)',
                    'rgba(75, 192, 192, 0.5)',
                    'rgba(153, 102, 255, 0.5)',
                    'rgba(255, 159, 64, 0.5)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
                display: true,
                text: "Lead Sources"
              }
        },

        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Image description

Conclusion 💡

By integrating Chart.js with Lightning Web Components, developers can create stunning data visualizations seamlessly integrated into Salesforce applications. This powerful combination empowers users to gain insights, make informed decisions, and unlock the full potential of their data.

References

Chart.js Documentation - (https://www.chartjs.org/docs/latest/)

Lightning Web Components Developer Guide - (https://developer.salesforce.com/docs/component-library/documentation/en/lwc)

Salesforce #LWC #ChartJS #DataVisualization #ExperienceCloud 📈💼

Top comments (0)