ChartJs in Lightning Components

ChartJs is an open source JavaScript library that allows us to create various types of charts, such as line, bar, pie, and stacked charts, and many more. The library can be explored at https://www.ChartJs.Org/.

In this section, we will see a simple example of how to include the ChartJs library in Lightning Components and build visualizations with a dataset. 

The steps to integrate this library are the same as those in the preceding sections. The ChartJs library works well under Locker Service so there are no extra transformations required to integrate it.

The steps to create a Lightning Component with ChartJs are as follows:

  1. Create a static resource hosting the ChartJs library; download the ChartJs library from this link: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js.
  1. Leverage the ltng:require tag and use the afterScriptsLoaded attribute to load the JavaScript files. The component code is as follows. Let's name the component file ChartJsDemo:
<aura:component>
<ltng:require scripts="{!$Resource.ChartJs}" afterScriptsLoaded="{!c.afterScriptsLoaded}"/>
<div class="chart-container">
<div class="pie-chart-container">
<canvas aura:id="piechart" id="piechart"/>
</div>
</div>
</aura:component>
  1. Use third-party JavaScript functions and code in the afterScriptsLoaded attribute:
({
afterScriptsLoaded : function(component, event, helper) {
var ctx = document.getElementById("piechart").getContext('2d');
var data = {
datasets: [{
data: [10, 20, 30],
backgroundColor: [
"Red",
"Green",
"#E9967A"
]
}],

// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Closed Cases',
'In Progress Cases',
'New Cases'
]
};
var myPieChart = new Chart(ctx,{
type: 'pie',
data: data
});

}
})
  1. The component will render as shown in the following screenshot:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.225