{"id":3395,"date":"2025-02-25T06:12:23","date_gmt":"2025-02-25T06:12:23","guid":{"rendered":"http:\/\/52.200.67.122\/blog\/?p=3395"},"modified":"2025-12-30T09:31:40","modified_gmt":"2025-12-30T09:31:40","slug":"hands-on-with-chart-js-inside-salesforce","status":"publish","type":"post","link":"https:\/\/www.differenzsystem.com\/blog\/hands-on-with-chart-js-inside-salesforce\/","title":{"rendered":"Hands On with Chart.js inside Salesforce"},"content":{"rendered":"\n<p>Throughout my journey as a developer, I\u2019ve realized the importance of effective data visualization, especially in Salesforce environments. Chart.js, a powerful and versatile JavaScript library, enables developers to create visually appealing and interactive charts that enhance data-driven decision-making.<\/p>\n\n\n\n<p>In this guide, I\u2019ll cover the basics of Chart.js, explain how to integrate it with Salesforce, and show you how to use it to enhance data presentation in your CRM.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Chart.js?<\/h2>\n\n\n\n<p><a href=\"https:\/\/www.chartjs.org\/\" target=\"_blank\" rel=\"noopener\">Chart.js<\/a> is a popular open-source JavaScript library that allows developers to create simple, flexible charts with minimal effort. It supports various chart types, including:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Bar Charts<\/strong>: Ideal for comparing different data categories.<\/li>\n\n\n\n<li><strong>Line Charts<\/strong>: Perfect for visualizing trends over time.<\/li>\n\n\n\n<li><strong>Pie and Doughnut Charts<\/strong>: Great for displaying proportional data.<\/li>\n\n\n\n<li><strong>Radar Charts<\/strong>: Useful for comparing multiple quantitative variables.<\/li>\n\n\n\n<li><strong>Bubble and Scatter Charts<\/strong>: Used for statistical analysis and illustrating relationships between variables.<\/li>\n<\/ul>\n\n\n\n<p>Since Chart.js is lightweight and responsive, it is a preferred option for Salesforce developers looking to enhance their dashboards with dynamic, interactive data visuals.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why use Chart.js with Salesforce?<\/h2>\n\n\n\n<p>Salesforce is a powerful CRM platform that helps businesses manage customer relationships and data. However, its reporting tools can sometimes be limited in interactivity and customization. Integrating Chart.js with Salesforce enables developers to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Enhance data presentation by creating visually engaging custom dashboards.<\/li>\n\n\n\n<li>Improve decision-making by displaying data in an easy-to-understand format.<\/li>\n\n\n\n<li>Customize charts to meet specific business needs.<\/li>\n\n\n\n<li>Ensure real-time updates by dynamically syncing Salesforce records with Chart.js components.<\/li>\n<\/ul>\n\n\n\n<p>By combining the power of Salesforce with the flexibility of Chart.js, you can create custom dashboards and reports that are visually appealing and easy to understand.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Getting Started with Setting Up Chart.js in a Salesforce Environment<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Setting Up Your Environment<\/h3>\n\n\n\n<p>Before integrating Chart.js, make sure you have a Salesforce Developer Edition or a Salesforce sandbox account where you can create and test your components.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Installing Chart.js<\/h3>\n\n\n\n<p>To use Chart.js in Salesforce, include its library in your Lightning Web Component (LWC). You can do this by:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/Chart.js\/2.8.0\/Chart.bundle.min.js\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Downloading the Chart.js file<\/a> (Open link -&gt; Right Click -&gt; Save As) and uploading it as a <strong>static resource<\/strong> in Salesforce.<\/li>\n\n\n\n<li>Alternatively, obtaining the library from the <strong>Chart.js website<\/strong> and saving it as <code>ChartJs<\/code> in your Salesforce static resources.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3. Creating a Lightning Web Component<\/h3>\n\n\n\n<p>Once Chart.js is installed, the next step is to create a Lightning Web Component that integrates it. Below is a sample implementation.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"576\" src=\"https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Lightning-Web-ChartJS-Component-1-1024x576.jpg\" alt=\"\" class=\"wp-image-3440\" title=\"\" srcset=\"https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Lightning-Web-ChartJS-Component-1-1024x576.jpg 1024w, https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Lightning-Web-ChartJS-Component-1-300x169.jpg 300w, https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Lightning-Web-ChartJS-Component-1-768x432.jpg 768w, https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Lightning-Web-ChartJS-Component-1-1536x864.jpg 1536w, https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Lightning-Web-ChartJS-Component-1-2048x1152.jpg 2048w, https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Lightning-Web-ChartJS-Component-1-30x17.jpg 30w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\"><strong>chart.js (JavaScript Controller)<\/strong><\/figcaption><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ chart.js \n \nimport {LightningElement, api, track} from 'lwc'; \nimport chartjs from '@salesforce\/resourceUrl\/ChartJs'; \nimport {loadScript} from 'lightning\/platformResourceLoader'; \nimport {ShowToastEvent} from 'lightning\/platformShowToastEvent'; \n\nexport default class Chart extends LightningElement { \n @api loaderVariant = 'base'; \n @api chartConfig; \n \n @track isChartJsInitialized; \n renderedCallback() { \n  if (this.isChartJsInitialized) { \n   return; \n  } \n  \/\/ load static resources. \n  Promise.all(&#91;loadScript(this, chartjs)]) \n   .then(() =&gt; { \n    this.isChartJsInitialized = true; \n    const ctx = this.template.querySelector('canvas.barChart').getContext('2d'); \n    this.chart = new window.Chart(ctx, JSON.parse(JSON.stringify(this.chartConfig))); \n    this.chart.canvas.parentNode.style.height = 'auto'; \n    this.chart.canvas.parentNode.style.width = '100%'; \n   }) \n   .catch(error =&gt; { \n    this.dispatchEvent( \n     new ShowToastEvent({ \n      title: 'Error loading ChartJS', \n      message: error.message, \n      variant: 'error', \n     })\n    );\n   });\n }\n}<\/code><\/pre>\n\n\n\n<p>In the above code, I have declared two @api attributes in the chart component<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>loaderVariant<\/strong>: Used to set the loader variant from the parent component.<\/li>\n\n\n\n<li><strong>chartConfig<\/strong>: Used to pass the chart settings and data from the parent component, allowing this component to be reused for different charts.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!-- chart.html --&gt; \n\n&lt;template&gt; \n\n   &lt;div class=\"slds-p-around_small slds-grid slds-grid--vertical-align-center slds-grid--align-center\"&gt;\n\n     &lt;canvas class=\"barChart\" lwc:dom=\"manual\"&gt;&lt;\/canvas&gt;\n     &lt;div if:false={isChartJsInitialized} class=\"slds-col--padded slds-size--1-of-1\"&gt;\n\n     &lt;lightning-spinner alternative-text=\"Loading\" size=\"medium\" variant={loaderVariant}&gt;&lt;\/lightning-spinner&gt;\n\n     &lt;\/div&gt;\n    &lt;\/div&gt;\n\n&lt;\/template&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. Fetching Data from Salesforce<\/h3>\n\n\n\n<p>Now, create an apex class to fetch the Opportunity Data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/chartdemo.cls\n\npublic class chartdemo\n{\n    @AuraEnabled(cacheable=true)\n    public static List&lt;AggregateResult&gt; getOpportunities()\n    {\n       return &#91;SELECT SUM(ExpectedRevenue) expectRevenue, SUM(Amount) amount, StageName stage\n\n       FROM Opportunity WHERE StageName NOT IN ('Closed Won') GROUP BY StageName LIMIT 20];\n\n    }\n }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. Integrating Data with the Chart Component<\/h3>\n\n\n\n<p><strong>chartDemo.js (JavaScript Controller)<\/strong> Create another Lightning Web Component, give it name as per your reference<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ chartDemo.js\n\nimport { LightningElement, wire } from 'lwc';\nimport getOpportunities from '@salesforce\/apex\/chartdemo.getOpportunities';\n\nexport default class ChartDemo extends LightningElement {\nchartConfiguration; \n    @wire(getOpportunities) \n    getOpportunities({ error, data }) { \n        if (error) { \n            this.error = error; \n            this.chartConfiguration = undefined; \n        } else if (data) { \n            let chartAmtData = &#91;]; \n            let chartRevData = &#91;]; \n            let chartLabel = &#91;]; \n            data.forEach(opp =&gt; { \n                chartAmtData.push(opp.amount); \n                chartRevData.push(opp.expectRevenue); \n                chartLabel.push(opp.stage); \n            }); \n            this.chartConfiguration = { \n                type: 'bar', \n                data: { \n                    datasets: &#91;{ \n                        label: 'Amount', \n                        backgroundColor: \"green\", \n                        data: chartAmtData, \n                    },{ \n                        label: 'Expected Revenue', \n                        backgroundColor: \"orange\", \n                        data: chartRevData, \n                    },], \n                    labels: chartLabel,\n                },\n                options: {},\n            };\n            console.log('data =&gt; ', data);\n            this.error = undefined;\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!-- chartDemo.html --&gt;\n\n&lt;template&gt;\n    &lt;lightning-card title=\"Open Opportunities\" icon-name=\"utility:chart\"&gt;\n        &lt;template if:true={chartConfiguration}&gt;\n            &lt;c-chart chart-config={chartConfiguration}&gt;&lt;\/c-chart&gt;\n        &lt;\/template&gt;\n    &lt;\/lightning-card&gt;\n&lt;\/template&gt;<\/code><\/pre>\n\n\n\n<p>In the HTML we have called the chart component and set the chart-config parameter.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">6. Adding the Component to a Lightning Page<\/h2>\n\n\n\n<p>Finally, add your new component to a Lightning page to view the chart in action. Edit a Lightning page and drag your component onto the page.<\/p>\n\n\n\n<p>Output:-<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"916\" height=\"518\" src=\"https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Chart.js-real-chart.png\" alt=\"\" class=\"wp-image-3457\" title=\"\" srcset=\"https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Chart.js-real-chart.png 916w, https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Chart.js-real-chart-300x170.png 300w, https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Chart.js-real-chart-768x434.png 768w, https:\/\/www.differenzsystem.com\/blog\/wp-content\/uploads\/2024\/09\/Chart.js-real-chart-30x17.png 30w\" sizes=\"auto, (max-width: 916px) 100vw, 916px\" \/><figcaption class=\"wp-element-caption\">Chart.js output<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Integrating Chart.js with <a href=\"https:\/\/www.differenzsystem.com\/salesforce-services\">Salesforce<\/a> gives businesses a powerful way to visualize and analyze data. Whether tracking sales performance, monitoring customer satisfaction, or generating real-time dashboards, Chart.js turns raw Salesforce data into actionable insights that are easy to interpret and share with your team.<\/p>\n\n\n\n<p>Data visualization is a powerful tool that can greatly enhance the decision-making process in any organization.<\/p>\n\n\n\n<p>With this hands-on guide, you can use Chart.js to create dynamic charts in your Salesforce applications and enhance your CRM data visualization.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQs<\/h2>\n\n\n\n<div class=\"wp-block-rank-math-faq-block\"><div class=\"rank-math-faq-item\"><h3 class=\"rank-math-question\">1. Can I use Chart.js with Salesforce reports?<\/h3><div class=\"rank-math-answer\">Yes, you can extract report data using Apex and visualize it using Chart.js.<\/div><\/div><div class=\"rank-math-faq-item\"><h3 class=\"rank-math-question\">2. Does Chart.js support real-time updates?<\/h3><div class=\"rank-math-answer\">Chart.js does not have built-in real-time support, but you can manually update the chart when Salesforce data changes.<\/div><\/div><div class=\"rank-math-faq-item\"><h3 class=\"rank-math-question\">3. What types of charts are supported?<\/h3><div class=\"rank-math-answer\">Chart.js supports bar, line, pie, radar, scatter, and more chart types, making it highly flexible for data visualization.<\/div><\/div><div class=\"rank-math-faq-item\"><h3 class=\"rank-math-question\">4. How do I deploy this component?<\/h3><div class=\"rank-math-answer\">You can add the LWC to a Lightning App Page or embed it in a Salesforce Lightning Record Page.<\/div><\/div><\/div>\n\n\n\n<p class=\"has-text-align-center\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Throughout my journey as a developer, I\u2019ve realized the importance of effective data visualization, especially in Salesforce environments. Chart.js, a powerful and versatile JavaScript library, enables developers to create visually appealing and interactive charts that enhance data-driven decision-making. In this guide, I\u2019ll cover the basics of Chart.js, explain how to integrate it with Salesforce, and [&hellip;]<\/p>\n","protected":false},"author":14,"featured_media":5080,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[66],"tags":[103,104,105,99],"class_list":["post-3395","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-salesforce-development","tag-chart-js","tag-javascript-library","tag-lightning-web-component","tag-salesforce"],"rank_math_description":"Learn to seamlessly integrate Chart.js with Salesforce for dynamic, interactive data visualizations. This guide walks you through setting up Chart.js in Salesforce.","category_names":["Salesforce Development"],"author_name":"Hiral Jariwala","post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/posts\/3395","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/comments?post=3395"}],"version-history":[{"count":29,"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/posts\/3395\/revisions"}],"predecessor-version":[{"id":6143,"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/posts\/3395\/revisions\/6143"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/media\/5080"}],"wp:attachment":[{"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/media?parent=3395"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/categories?post=3395"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.differenzsystem.com\/blog\/wp-json\/wp\/v2\/tags?post=3395"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}