Throughout my journey as Developer, I’ve realised the importance of visualising data effectively, especially in Salesforce environments. That’s where Chart.js, a powerful and versatile JavaScript library, comes into play.
In this article, I’ll guide you through the basics of Chart.js, how it integrates with Salesforce, and why it’s a must-have tool for anyone looking to enhance their data presentations.
Chart.js is a popular open-source JavaScript library that enables developers to create simple yet flexible charts with minimal effort. It supports a variety of chart types, including bar, line, pie, radar, and more, making it a go-to choice for developers who need to visualise data quickly and effectively.
Salesforce is a powerful CRM platform that helps businesses manage their customer relationships and data. By integrating Chart.js with Salesforce, we can enhance our data presentation and make it more insightful for users.
This integration allows us to create custom dashboards and reports that are visually appealing and easy to understand.
Before we begin, ensure that you have a Salesforce Developer Edition or a Salesforce sandbox account where you can create and test your components.
To use Chart.js in Salesforce, you need to include the Chart.js library in your Lightning Web Component (LWC). You can do this by downloading this ChartJs file(Open link -> Right Click -> Save As) or you can also download the library from the Chart.js website, and upload it into a static resource with the name ‘’ChartJs”.
Next, create a new Lightning Web Component in Salesforce. Here is a basic example of how to integrate Chart.js into your component:
// chart.js
import {LightningElement, api, track} from 'lwc';
import chartjs from '@salesforce/resourceUrl/ChartJs';
import {loadScript} from 'lightning/platformResourceLoader';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class Chart extends LightningElement {
@api loaderVariant = 'base';
@api chartConfig;
@track isChartJsInitialized;
renderedCallback() {
if (this.isChartJsInitialized) {
return;
}
// load static resources.
Promise.all([loadScript(this, chartjs)])
.then(() => {
this.isChartJsInitialized = true;
const ctx = this.template.querySelector('canvas.barChart').getContext('2d');
this.chart = new window.Chart(ctx, JSON.parse(JSON.stringify(this.chartConfig)));
this.chart.canvas.parentNode.style.height = 'auto';
this.chart.canvas.parentNode.style.width = '100%';
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error loading ChartJS',
message: error.message,
variant: 'error',
})
);
});
}
}
In the above code, I have declared two @api attributes in the chart component
<!-- chart.html -->
<template>
<div class="slds-p-around_small slds-grid slds-grid--vertical-align-center slds-grid--align-center">
<canvas class="barChart" lwc:dom="manual"></canvas>
<div if:false={isChartJsInitialized} class="slds-col--padded slds-size--1-of-1">
<lightning-spinner alternative-text="Loading" size="medium" variant={loaderVariant}></lightning-spinner>
</div>
</div>
</template>
Now, create an apex class to fetch the Opportunity Data.
//chartdemo.cls
public class chartdemo
{
@AuraEnabled(cacheable=true)
public static List<AggregateResult> getOpportunities()
{
return [SELECT SUM(ExpectedRevenue) expectRevenue, SUM(Amount) amount, StageName stage
FROM Opportunity WHERE StageName NOT IN ('Closed Won') GROUP BY StageName LIMIT 20];
}
}
Create another Lightning Web Component, give it name as per your reference
// chartDemo.js
import { LightningElement, wire } from 'lwc';
import getOpportunities from '@salesforce/apex/chartdemo.getOpportunities';
export default class ChartDemo extends LightningElement {
chartConfiguration;
@wire(getOpportunities)
getOpportunities({ error, data }) {
if (error) {
this.error = error;
this.chartConfiguration = undefined;
} else if (data) {
let chartAmtData = [];
let chartRevData = [];
let chartLabel = [];
data.forEach(opp => {
chartAmtData.push(opp.amount);
chartRevData.push(opp.expectRevenue);
chartLabel.push(opp.stage);
});
this.chartConfiguration = {
type: 'bar',
data: {
datasets: [{
label: 'Amount',
backgroundColor: "green",
data: chartAmtData,
},{
label: 'Expected Revenue',
backgroundColor: "orange",
data: chartRevData,
},],
labels: chartLabel,
},
options: {},
};
console.log('data => ', data);
this.error = undefined;
}
}
}
<!-- chartDemo.html -->
<template>
<lightning-card title="Open Opportunities" icon-name="utility:chart">
<template if:true={chartConfiguration}>
<c-chart chart-config={chartConfiguration}></c-chart>
</template>
</lightning-card>
</template>
In the HTML we have called the chart component and set the chart-config parameter.
Finally, add your new component to a Lightning page to see the chart in action. You can do this by editing a Lightning page and dragging your component onto the page.
Output:-
Data visualisation is a powerful tool that can significantly enhance the decision-making process in any organisation. By using Chart.js within Salesforce, you can transform raw data into actionable insights that are easy to interpret and share with your team.
Whether you’re presenting sales performance, tracking customer satisfaction, a well-designed chart can make all the difference.
Thank you for reading, and happy coding!