Display Bar Chart

Learn How to Display Bar Chart in Salesforce Lightning Web Component


The graphical representation of information and data is known as data visualization. Data visualisation tools make it easy to see and understand trends, outliers, and patterns in data by using visual elements including charts, graphs, and maps. Any company's executives and managers want to see their data visualized in a way that gives them insights.

ChartJS is one such visualization library that is both common and open source. For designers and developers, it's an easy but versatile JavaScript charting. Let's look at how we can use ChartJs to draw charts on a lightning web component in this article.

In this blog, I'll show you how to use apex to get data from a Salesforce object and feed it into a bar chart. In addition, an aggregate query will be used to summarise the data, and the data will be presented in two datasets. I used two LWCs to build the UI. One is a parent, while the other is a child component.

The parent component will handle most of the data processing and transfer an attribute (chartConfiguration) to the child component. We're attempting to illustrate an Opportunity Bar Chart with Estimated Revenue & Sum for different stages in this article.

Prerequisite to be followed before starting the process

Download the ChartJS file here and save it as a static resource called "ChartJS."


Create a Lightning Web Component named childbarchart and paste the code below into it.

dont miss out iconDon't forget to check out: 5 Groundbreaking Features Exclusive to Salesforce Lightning Experience


    <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="base"></lightning-spinner>


import { LightningElement, api } from 'lwc';
import chartjs from '@salesforce/resourceUrl/ChartJs';
import { loadScript } from 'lightning/platformResourceLoader';
import { ShowToastEvent } from 'lightning/platformShowToastEvent'; 
export default class childbarchart extends LightningElement {
    @api chartConfig; 
    renderedCallback() {
        if (this.isChartJsInitialized) {
        // load chartjs from the static resource
        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)));
        .catch(error => {
                new ShowToastEvent({
                    title: 'Error loading Chart',
                    message: error.message,
                    variant: 'error',


public class BarChartController {
    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 a new LWC as the parentComponent that will handle all of the data entry for us.


    <lightning-card title="Open Opportunities" icon-name="utility:chart">
        <template if:true={chartConfiguration}>
            <c-child-bar-chart chart-config={chartConfiguration}></c-child-bar-chart>


import { LightningElement, wire } from 'lwc';
import getOpportunities from '@salesforce/apex/BarChartController.getOpportunities'; 
export default class ParentBarchart extends LightningElement {
    getOpportunities({ error, data }) {
        if (error) {
            this.error = error;
            this.chartConfiguration = undefined;
        } else if (data) {
            let chartAmtData = [];
            let chartRevData = [];
            let chartLabel = [];
            data.forEach(opp => {
            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;

dont miss out iconCheck out another amazing blog by Anuj here: Best Practices To Be Followed In Salesforce Lightning Web Components


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">


  1. When adding LWC to a tab I get the error.

    Validation Errors While Saving Record(s)
    There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "We couldn't validate your component c:parentBarchart used in Custom Tab. Review it and try again.".

    Do you know the solution?
    Sorry for my English, thanks.

Popular Salesforce Blogs

AI in Salesforce

Transform businesses with the power of Artificial Intelligence leveraged through Salesforce Einstein

Blog in

Artificial Intelligence is powering next-generation customer experiences with smart predictions, intelligent recommendations, timely automation and much more. Gartner predicts that by 2020, a staggering 85% of…