Two Time-Saving Tips When Using Loading Spinners In Lightning Web Components (LWC)

Two Time-Saving Tips When Using Loading Spinners In Lightning Web Components (LWC)

Quickest Way To Show/Hide It & Bind It Inside An Element

The Quickest Way To Show/Hide Loading Spinner

cmp.html

<lightning-spinner
    lwc:if={isLoading}
    alternative-text="Loading..."
    variant="brand"
>
</lightning-spinner>

cmp.js

isLoading = false; //true - shows spinner, false - hides spinner
//can we toggeled like this.isLoading = true; OR this.isLoading = false;

Example Usage

loadData(){
    this.isLoading = true;
    //do something
    this.isLoading = false;
}

Example Usage With Promises or Imperative Apex Calls

handleLoad() {
    this.isLoading = true;
    getContactList()
        .then((result) => {
            this.contacts = result;
        })
        .catch((error) => {
            this.error = error;
        }).finally(() => {
            this.isLoading = false;
        });
}

Limiting The Spinner To Be Bound Inside An Element

Did you ever add a spinner to your component but it ended up covering the whole page / going out of where it's supposed to be?

💡
Adding the class slds-is-relative to the parent/container element that contains the spinner makes the spinner bound inside that element and not go outside of its boundary
<div class="slds-is-relative">
    <lightning-spinner
      lwc:if={isLoading}
      alternative-text="Loading..."
      variant="brand"
    >
    </lightning-spinner>
</div>