You are currently viewing How To Create A Custom Dashboard In LWC Using JavaScript Libraries

How To Create A Custom Dashboard In LWC Using JavaScript Libraries

Sharing is caring!

When it comes to web development, creating custom dashboards is an integral part of providing users with intuitive interfaces to visualize data. Custom dashboards allow users to interact with data in a meaningful way, providing insights & enabling informed decisions. 

Developers leverage Lightning Web Components (LWC) with JavaScript libraries to craft dynamic, interactive, & visually appealing dashboards tailored to specific needs.  

In this blog, we’ll dive deep into creating a custom dashboard in Lightning Web Components (LWC) using JavaScript libraries.

Understanding LWC & Its Benefits

Lightning Web Components is a cutting-edge JavaScript framework tailored to craft web components within Salesforce applications. It leverages the most up-to-date web standards to empower developers to build robust solutions.

LWC provides a robust architecture for building responsive and scalable applications with reusable components. Developers can easily create dynamic user interfaces by leveraging the power of JavaScript, HTML, and CSS.

What Makes LWC Unique?

  1. Enhanced Performance: LWC delivers better performance than its predecessors, thanks to its lightweight architecture and optimized rendering engine.
  1. Reusability: Components built with LWC are highly reusable, promoting code modularity and reducing development time.
  1. Seamless Integration: LWC integrates with other Salesforce technologies and frameworks, providing a cohesive development experience.

Introduction To Custom Dashboards

Custom dashboards are powerful web development tools that provide users with a visual representation of data relevant to their needs. 

Whether tracking sales, monitoring website traffic, or analyzing user behavior, custom dashboards offer insights at a glance. They offer a tailored solution for displaying key performance indicators (KPIs), metrics, and insights in a visually appealing format. 

By integrating JavaScript libraries into LWC, developers can enhance the functionality and aesthetics of their dashboards, empowering users with an intuitive & highly interactive experience.

Overview Of JavaScript Libraries

JavaScript libraries play a crucial role in web development. They provide pre-written JavaScript code to simplify complex tasks and streamline development processes. These libraries offer various functionalities, from DOM manipulation to data visualization.

JavaScript libraries enable developers to leverage existing solutions and focus on application logic rather than reinventing the wheel. They promote code efficiency, reduce development time, and ensure cross-browser compatibility.

Types Of JavaScript Libraries

Some popular JavaScript libraries for building custom dashboards include:

  • D3.js: A powerful library renowned for its prowess in data visualization, providing an extensive array of chart types and flexible customization features.
  • Chart.js: An easy-to-use library for creating responsive and interactive charts, ideal for displaying data in a visually appealing manner.
  • ApexCharts: A modern JavaScript charting library supporting dynamic data, animations, and advanced features.

Prerequisites For Creating A Custom Dashboard

Before creating your custom dashboard in our Lightning Web Component, we must ensure that we have access to the necessary JavaScript libraries. 

Since Salesforce restricts external links within its environment, we must access and upload the JavaScript library as a Static Resource in the Salesforce org. This aligns with LWC’s content security policy. 

You can download the Charts library file to your system from the provided link or visit the official website of the respective library for the latest versions. 

Once the library file is obtained, we can build interactive dashboard in Lightning Web Component.

Steps To Create A Custom Dashboard 

Step 1: First, log in to your Salesforce Org and Upload the downloaded library to the Static Resource of your Salesforce Org. 

Step 2: Then, we need to build a Lightning Web Component in which we want to represent our Salesforce data as a dashboard.

  • Open VSCode and then create a New Project.  
  • Authorize Your Org  
  • Then create a Lightning Web Component.
  • We have named the LWC Component  “AllOpportunitiesByStage” since we will display all the Opportunities along with their Stage.

You will get these three files in the Lightning Component Bundle.

  • Markup File (HTML File)
  • JS Controller (JavaScript File)
  • Meta-Data File (XML File)

You will be getting something like this.

Step 3: Along with these three files, we must create an APEX Controller to provide the data from our Salesforce Org to our Lightning Web Component. 

Besides, in this Apex Class, we must define a static method with the “@AuraEnabled” notation to be called from the Lightning Web Component. 

In addition, this method will query all the Opportunities along with their StageName from Our Salesforce Org and return the data in a List of wrappers containing StageName and Number of Opportunities.

  1. Go To Dev Org.
  2. Gear Icon.
  3. Open Developer Console.
  4. File.
  5. New.
  6. Apex Class Name it “AllOpportunitiesByStageNameController.”

Define a method inside the class as given below.

Apex Controller (AllOpportunitiesByStageNameController):

public class AllOpportunitiesByStageNameController {


    public static List<wrapper> getOpportunity(){


            List<AggregateResult> agrResult = [select Count(Id), StageName from Opportunity Group By StageName];

            List<wrapper> wrapperList = new List<wrapper>();


                for(AggregateResult ar : agrResult){

                    wrapper obj = new wrapper();

                    obj.count = Integer.valueOf(ar.get(‘expr0’));

                    obj.stage = String.valueOf(ar.get(‘StageName’));




            return wrapperList;

        }catch(Exception ex){

            System.debug(‘Found Error ‘+ex.getMessage()+’ at Line ‘+ex.getLineNumber());

            return null;



    public class wrapper{

        @AuraEnabled public Integer count;

        @AuraEnabled public String stage;



Step 4: We have configured our Apex Controller, and now we have to create a child Lightning Web Component to process the data and create a chart.

Then, in the Parent Component, we will call the Apex controller, query all the data, and pass it on to the Child Component. Additionally, we’ll render the chart by utilizing the data transmitted from the parent component to the child component.

Child Component:

  • In the Markup File (Child.html), add the following code:


    <lightning-card title=”Doughnut Chart”>

        <div class=”slds-p-around_small slds-grid slds-grid–vertical-align-center slds-grid–align-center”>

            <canvas class=”chart” 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>





  • In the JS Controller (Child.js), add the following Code.

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 Child extends LightningElement {

@api loaderVariant = ‘base’;

@api labels;

@api values;

@api config={

  type: ‘doughnut’,

  data: {

          labels: [“A”, “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “J”],

          datasets: [{

            label: ‘My First Dataset’,

            data: [1,2,3,4,5,6,7,8,9,10],

            backgroundColor: [‘rgb(0,255,255)’,’rgb(54, 162, 235)’,’rgb(255, 205, 86)’,’rgb(255,0,255)’,’rgb(54, 45, 235)’,’rgb(255, 205, 86)’,’rgb(255, 99, 132)’,’rgb(200, 162, 235)’,’rgb(0,255,0)’,’rgb(255,0,0)’,],

            hoverOffset: 4





    if(this.labels){ = this.labels;[0].label = ‘All Opportunities By Stage’;


    if(this.values){[0].data = this.values;



 @track isChartJsInitialized;

 renderedCallback() {

  // load static resources.

  Promise.all([loadScript(this, chartjs)])

   .then(() => {

    this.isChartJsInitialized = true;

    const ctx = this.template.querySelector(‘canvas.chart’).getContext(‘2d’);

    this.chart = new window.Chart(ctx, JSON.parse(JSON.stringify(this.config))); = ‘auto’; = ‘100%’;


   .catch(error => {


     new ShowToastEvent({

      title: ‘Error loading ChartJS’,

      message: error.message,

      variant: ‘error’,






  • In the Meta-Data File (Child.xml), add the following Code.

<?xml version=”1.0″ encoding=”UTF-8″?>

<LightningComponentBundle xmlns=””>








Step 5: We have configured the Child Component, which will render a chart created by the data we passed into it. After that, we need to configure the Parent Component to call the Apex class, manage all the data, and pass it on to the child component.

Parent Component:

  • Add the following code in the Markup File of the Parent Component (AllOpportunitiesByStage.html).


    <lightning-card title=”This is the Chart Opportunity By StageName”>

        <template if:true={ischildLoaded}>

            <c-child labels={labels} values={values}></c-child>




  • Add the following code in the JS Controller of the Parent Component (AllOpportunitiesByStage.js).

import { LightningElement, api, track } from ‘lwc’;

import getOpportunity from ‘@salesforce/apex/AllOpportunitiesByStageNameController.getOpportunity’;

export default class AllOpportunitiesByStage extends LightningElement {

    @api labels = [];

    @api values = [];

    @track ischildLoaded = false;



        .then(result =>{

            for(var key in result){




            this.ischildLoaded = true;


        .catch(error =>{

            console.log(‘Found Error in JS >>> ‘,error);



  • Add the following code to the Parent Component’s Meta-Data File (AllOpportunitiesByStage.xml).

<?xml version=”1.0″ encoding=”UTF-8″?>

<LightningComponentBundle xmlns=””>








Step 6: We have created our Lightning Web Component. Now, it’s time to deploy it to Salesforce Org and Add it to your Lightning App Page or Lightning Record Page.

  1. Right-click on Your Component SFDX. Deploy This Source to Org. Once your code is successfully deployed to the org, open your browser and log into your Org.
  1. Then Go To Setup; search Lightning App Builder in the Quick Find Box.
  1. Click New App Page. Then click Next.
  1. Next, enter the name of the app page and click Next.
  1. Header and Right Sidebar, then click on Finish.
  1. Search for AllOpportunitiesByStage Component and then drag it to the Empty Section. Next, Save and Activate the App Page.
  1. Go To App Launcher and then search For Opportunity AppPage. Open it.
  1. After Clicking on it, you will be redirected to your dashboard.

Final Words

Creating a custom dashboard in LWC using JavaScript libraries offers a powerful solution for data visualization and user engagement in web applications. 

By following best practices in development, integration, and optimization,  developers can build feature-rich dashboards that deliver valuable insights to users & empower them to make data-driven decisions with ease. LWC provides responsive design features, and JavaScript libraries offer responsive charting options for dynamic layouts. 

Whether you’re tracking sales performance, monitoring key metrics, or analyzing customer behavior, custom dashboards offer a powerful solution for visualizing data in Salesforce.

Ready to elevate your Salesforce Lightning skills and create stunning custom dashboards in LWC? Choose Cloud Analogy, a leading Salesforce Consulting Partner, to unlock the full potential of Lightning Web Components with our comprehensive consulting services and expert guidance & embark on a journey to transform your business processes into streamlined, efficient workflows. 

From implementation to optimization, we’re here to help you leverage the power of Salesforce to drive growth and success. Hire one of the best Salesforce Consulting Partners now!


Ajay Dubedi

CEO | Founder
Ajay Dubedi, the founder and CEO of Cloud Analogy, is a prominent Salesforce Sales, Service, and Marketing cloud Consultant with a rich expertise in handling challenging business models. Ajay has assisted and implemented solutions in industries comprising Banking, Health Care, Networking, Education, Telecommunication and Manufacturing. Ajay is globally acclaimed for his extensive experience in APEX Programming, VisualForce pages, Triggers, Workflows, Page Layouts, Roles, Profiles, Reports & Dashboards.

Hire the best Salesforce Implementation Partner. Choose Cloud Analogy, the world's most preferred Salesforce Implementation Company that provides custom CRM Implementation services.

Leave a Reply

× How can I help you?