What is Spinner?
You can show the progress of a task in salesforce lightning or visualforce through loading spinner. Spinners in lightning are easy to use and customize.
You can also use it for a child component or a particular div or section only.
What is lightning:spinner?
It is a lightning component used to show the spinner. You can also customize its size and variant and you can also add your custom style class to it.
Working Demo:
Step-1: Create SpinnerConroller.cls
Here we are just creating a basic Apex class to fetch records from Account object and returning them.
1 2 3 4 5 6 7 8 9 10 |
public with sharing class SpinnerController { @AuraEnabled public static List<Account> fetchRecords( ) { return [SELECT id, name FROM Account LIMIT 5000]; } } |
Step-2: Open Spinner.cmp and paste below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<aura:component controller="SpinnerController" > <aura:attribute name="recordsData" type="Account[]" description="account Records Data" /> <lightning:spinner aura:id="Spinner" alternativeText="Loading" size="medium" variant="brand" class="slds-hide"/> <lightning:button variant="brand" label="Fetch Records" title="Fetch Records" onclick="{! c.fetchData }" /><br/><br/> <aura:iteration var="account" items="{!v.recordsData}" indexVar="index" > <p class="slds-p-horizontal_small"> {! (index+1) + ' - ' + account.Name } </p> </aura:iteration> </aura:component> |
Step-3: Open SpinnerController.js and paste the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
({ fetchData : function(component, event, helper) { helper.showSpinner(component); var action = component.get('c.fetchRecords'); action.setCallback(this,function(response){ if(response.getState() === 'SUCCESS') { component.set('v.recordsData',response.getReturnValue()); } else if(response.getState() === 'INCOMPLETE') { component.set('v.message','No Server Response or client is offline'); } else if(response.getState() === 'ERROR') { component.set('v.message','Error'); } helper.hideSpinner(component); }); $A.enqueueAction(action); }, }) |
Step-4: Open SpinnerHelper.js and paste the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
({ showSpinner: function(component) { var spinnerMain = component.find("Spinner"); $A.util.removeClass(spinnerMain, "slds-hide"); }, hideSpinner : function(component) { var spinnerMain = component.find("Spinner"); $A.util.addClass(spinnerMain, "slds-hide"); }, }) |
Step-5: Open DemoApp.app and call the component
1 2 3 |
<c:Spinner /> |
Our component is now ready to use.
You can manually control the show/hide of spinner here, it will not be handled automatically. If you want it to automatic show or hide on some processing, you can use system events for this. Check Below post.