Create a Custom Spinner In Salesforce Lightning Web Components

We have all been in the situation where we are uploading a file or reloading a page, then during that time frame, a spinner is rotating on the page, till the page or file loads. This spinner indicates that the load process is running in the background and disappears after the page has loaded.

In this blog, we will explore how to create a custom spinner in Salesforce Lightning Web Components, allowing you to utilize it within your Salesforce instance.

We will see the following scenarios of adding the Spinner in the LWC.

  • Create a custom spinner in Lightning Web Component
  • Display text and change color in the custom spinner in Lightning Web Component
  • Displaying a spinner while fetching data from Apex

What is Lightning Spinner in LWC?

A Lightning Spinner in Lightning Web Component is a built-in component that we add using the <lightning-spinner> tag, which displays a spinning animation while something is loading, such as fetching data or performing a time-consuming task.

It helps users know that the system is working in the background. This spinner is useful when a delay occurs, typically when uploading a large file or reloading a page, so users don’t think the app or page is stuck.

Create a Custom Spinner In Lightning Web Component

In the steps below, we will create a sample spinner to display in the Lightning Web Component. The spinner component requires a trigger to be displayed, which is typically the loading of a page or a record in real-time.

In this example, we will trigger the lighting spinner using the button trigger. Now, follow the steps below to create a spinner in Lightning Web Component.

In the VS Code IDE, press the keys “Ctrl + Shift + P” and in the command palette, enter the component name, such as spinnerLWC, then press Enter.

Now, you will get three files, spinnerLWC.html, spinnerLWC.js and spinnerLWC-meta.xml

We will define the logic to trigger the display of the LWC spinner in the JS file using the code below.

import { LightningElement, api } from 'lwc';
export default class LightningSpinnerLWCSimpleExample extends LightningElement {
    @api isLoaded = false;

    handleClick() {
        this.isLoaded = !this.isLoaded;
    }
}

To add the lightning-spinner to the web component, use the code below in the spinnerLWC.html file.

<template>
    <lightning-button label="Toggle" variant="brand" onclick={handleClick}>
    </lightning-button>
    <div class="slds-m-around_large">
        <p if:true={isLoaded}>Content has been loaded.</p>
         <div if:false={isLoaded} class="slds-is-relative">
            <lightning-spinner
                alternative-text="Loading..." variant="brand">
            </lightning-spinner>
        </div>
    </div>
</template>

In the above code, we have used the built-in component <lightning-spinner> to add the spinner in the Lightning web component.

Expose the Lightning Web Component to the Lightning pages using the code below in the meta.xml file inside the <LightningComponentBundle> tag.

<isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

Now, to deploy this lightning web component, navigate to the lightning page and click on the settings icon, and select Edit Page.

Custom Spinner in Salesforce lightning web component

In the Lightning app builder, drag the Lightning Web Component (LWC) spinner to the Lightning page and save the changes.

Add Spinner in Salesforce LWC

To view the lightning spinner, click on the toggle button, and as we click on it, the Lightning spinner will appear on the page.

How to add load Spinner in LWC

This way, we can add the spinner in the Lightning Web Component using the lightning-spinner element.

Display Text and Change Color for Spinner in Lightning Web Component

We can also add some enhancements to the lightning-spinner, such as changing the color of the spinner and displaying text below it. Let’s see how we can do that.

Display Text Below the Lightning Spinner

In the Lightning-spinner component, there is no functionality to display text below the lightning-spinner. However, we can utilize the Salesforce Lightning Design System in HTML to add a single element that displays the text.

Add the code below the <lightning-spinner>.

<lightning-spinner 
                        alternative-text="Loading..." 
                        variant="brand">
                    </lightning-spinner>
                    
                    <div class="slds-spinner_container">
                        <div class="slds-spinner--brand  slds-spinner slds-spinner--large slds-is-relative">
                          <span class="slds-assistive-text">Loading</span>
                          <div class="slds-spinner__dot-a"></div>
                          <div class="slds-spinner__dot-b"></div>
                        </div>
                          <p class="slds-spinner-text">Hang on...</p>
                        </div>

Using the SLDS and the paragraph tag <p>, the message will be visible on the lightning web component along with the spinner.

To adjust the text and display it below the spinner, we need to apply the CSS. For this, create a .CSS file in the same component and enter the code below.

.slds-spinner-text {
    width: 320px;
    text-align: center;
    font-weight: bold;
    font-size: 16px;
    position: absolute;
    bottom: 1px;
    left: 50%;
    transform: translateX(-50%);
}

.slds-spinner--small .slds-spinner-text {
    transform: translate(-36%, -50%) rotate(-90deg);
}

.slds-spinner--medium .slds-spinner-text {
    transform: translate(-32%, -50%) rotate(-90deg);
}

.slds-spinner--large .slds-spinner-text {
    transform: translate(-26%, -50%) rotate(-90deg);
}

If the code is not appearing just below the spinner, you can also adjust the text by changing the key values in the .slds-spinner-text.

Now, refresh the page. If the changes are still not visible, open the page in Edit mode in Lightning App Builder again and save the changes.

Add text below spinner in Salesforce LWC

This way, we can add a display text below the lightning-spinner in the Lightning Web Components.

Change the Color of the Lightning Spinner

The default lightning-spinner is blue in colour, which we can also change. The default color of the lightning-spinner is always gray.

If you define the <lightning-spinner> without a variant, it will appear in gray, as shown below.

Change spinner color in Salesforce LWC

To change the color, we define the variant as “brand,” then the spinner will change color according to the brand color.

For example, in my org, the brand color is “lightning blue“, then the spinner will appear blue.

Custom Lightning spinner in LWC

To change the brand color, navigate to the setup > quick find > Themes and Branding.

how to change spinner color in Salesforce LWC

In the setup of Themes and Branding, you will see multiple themes. Here, you can theme to any other from the default Lightning blue. For example, if I change the theme to “Codey Canyon,” it will change the color to orange for the whole org.

Add a Custom Spinner on page load in LWC

With this theme, if you select the variant as brand, then the spinner will appear in orange color. However, this will change the color of the entire organization according to the selected theme.

Add Variant in LWC spinner in salesforce

This way, we can change the color of the lightning spinner by defining the variant of the lightning-spinner component.

Displaying a Spinner While Fetching Data From Apex

Now, we will see a real-time example where we retrieve data in the LWC using the Apex controller class and display a loading spinner while waiting for data to load from the server (Apex controller), and hide the spinner once the data is displayed.

First, create the controller class to fetch the data. In this example, I’ve created the controller class SpinnerController to fetch the Account records.

public with sharing class SpinnerController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getData() {
        return [SELECT Id, Name FROM Account LIMIT 10];
    }
} 

Now, create a Lightning Web Component spinnerApex, and enter the below code in the spinnerApex.js to define the logic to get the records from the controller class, and also display the spinner in the LWC.

Here, we have imported the Apex controller class using the import getData statement.

import { LightningElement, track } from 'lwc';
import getData from '@salesforce/apex/SpinnerController.getData';

export default class SpinnerApex extends LightningElement {
    @track data;
    @track error;
    @track isLoading = false;

    connectedCallback() {
        this.fetchData();
    }

    fetchData() {
        this.isLoading = true;
        getData()
            .then(result => {
                this.data = result;
                this.isLoading = false;
            })
            .catch(error => {
                this.error = error.body.message;
                this.isLoading = false;
            });
    }
}

In the code above, we have used connectedCallback(), which calls fetchData(), to get data from the Apex method getData. It shows the spinner during loading and returns either data or an error based on the result.

After this, enter the code below in the HTML file to define the spinner component that will be displayed till data is displayed.

<template>
    <lightning-spinner if:true={isLoading} size="large"></lightning-spinner>
    <template if:true={data}>
        <div>
            <h2>Data Loaded:</h2>
            <ul>
                <template for:each={data} for:item="item">
                    <li key={item.Id}>{item.Name}</li>
                </template>
            </ul>
        </div>
    </template>
    <template if:true={error}>
        <p class="slds-text-color_error">{error}</p>
    </template>
</template>

This template shows a loading spinner <lightning-spinner> while data is being fetched (isLoading = true). After fetching, it displays a list of account records, and the spinner will disappear.

Make the component visible to the Lightning pages using the code below in the meta.xml file inside the <LightningComponentBundle> tag.

<isExposed>true</isExposed>
    <targets>
         <target>lightning__AppPage</target>
         <target>lightning__RecordPage</target>
    </targets>

Go to the Lightning page and, to deploy the Lightning web component, click the settings icon, then select Edit page.

In the Lightning App builder, drag the spinner LWC component to the page and save the changes.

Now, on the Lightning page, you will see that, while loading the Lightning web component, the Lightning spinner will appear on the screen before displaying the records.

Custom Lightning Spinner in Salesforce LWC

This way, we can display the spinner while fetching the data from any source, like an Apex class. This is useful when the load data is in large volume, as it shows that the data loading process is running in the background.

This is how we can create and use a custom loading spinner in Salesforce using Lightning Web Components. With this approach, you can display a spinner during data fetch, file upload, or any other background process to enhance the user experience and display a visual sign of data loading.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.