chartExample.js
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import ChartJS from '@salesforce/resourceUrl/ChartJS';
export default class ChartExample extends LightningElement {
chart;
chartJsInitialized = false;
renderedCallback() {
if (this.chartJsInitialized) {
return;
}
this.chartJsInitialized = true;
Promise.all([loadScript(this, ChartJS)])
.then(() => {
const ctx = this.template.querySelector('canvas').getContext('2d');
this.chart = new window.Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{
label: 'Revenue',
data: [100, 200, 300],
backgroundColor: 'rgba(54, 162, 235, 0.6)'
}]
}
});
})
.catch(error => {
console.error('Error loading ChartJS', error);
});
}
}