+ Start a Discussion
Andrew Aldis 15Andrew Aldis 15 

Add pagination to a Lightning Datatable

I created a lightning:datatable to show a number of records and need to add pagination to it.  The table has sorting which is a requirement and must be done on the client side.  Is there a way to add pagination to a lightning datatable?
Ajay K DubediAjay K Dubedi
Hi Andrew,

Please refer the below code for pagination in lightning datatable. Hope it helps you.

// Component

<aura:component controller="DataTableWithPagenation">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="Accounts" type="Account[]"/>
    <aura:attribute name="page" type="integer" description="using for store page Number"/>
    <aura:attribute name="pages" type="integer" description="using for store All Pages page Number"/>
    <aura:attribute name="total" type="integer" description="total records count store "/>
    <aura:attribute name="mycolumns" type="List"/>
    <div class="slds-m-around_small">
        <div class="slds-page-header" role="banner">
            <p class="slds-page-header__title slds-truncate">{!v.total} Accounts • page {!v.page} / {!v.pages}</p>
            <ui:inputSelect aura:id="recordSize" label="Display Record Per Page: " change="{!c.onSelectChange}">
                <ui:inputSelectOption text="10" label="10" value="true"/>
                <ui:inputSelectOption text="15" label="15"/>
                <ui:inputSelectOption text="20" label="20"/>
        <p class="slds-p-horizontal_small slds-box">
            <lightning:datatable data="{!v.Accounts}" columns="{! v.mycolumns }" keyField="id"  />
        <div class="slds-align_absolute-center">            
            <lightning:button disabled="{!v.page == 1}" variant="brand" label="Previous Page" onclick="{! c.navigate }" />            
            <lightning:button disabled="{!v.page == v.pages}" aura:id="previousPage" variant="brand" label="Next Page" onclick="{! c.navigate }" />

//js Contoller

   doInit: function(component, event, helper) {
      // this function call on the component load first time     
      // get the page Number if it's not define, take 1 as default
      var page = component.get("v.page") || 1;
      // get the select option (drop-down) values.   
      var recordToDisply = component.find("recordSize").get("v.value");
       component.set('v.mycolumns', [
                   {label: 'Account Name', fieldName: 'Name', type: 'Name',sortable:'true'},                   
                {label: 'Phone', fieldName: 'Phone', type: 'Phone',sortable:'true'},
                {label: 'Email ID', fieldName: 'Email_ID__c', type: 'Email',sortable:'true'}
      // call the helper function   
      helper.getAccounts(component, page, recordToDisply);
   navigate: function(component, event, helper) {
      // this function call on click on the previous page button  
      var page = component.get("v.page") || 1;
      // get the previous button label  
      var direction = event.getSource().get("v.label");
      // get the select option (drop-down) values.  
      var recordToDisply = component.find("recordSize").get("v.value");
      // set the current page,(using ternary operator.)  
      page = direction === "Previous Page" ? (page - 1) : (page + 1);
      // call the helper function
      helper.getAccounts(component, page, recordToDisply);
   onSelectChange: function(component, event, helper) {
      // this function call on the select opetion change,     
      var page = 1
      var recordToDisply = component.find("recordSize").get("v.value");
      helper.getAccounts(component, page, recordToDisply);

//js Helper

   getAccounts: function(component, page, recordToDisply) {
      // create a server side action. 
      var action = component.get("c.fetchAccount");
      // set the parameters to method 
         "pageNumber": page,
         "recordToDisply": recordToDisply
      // set a call back   
      action.setCallback(this, function(a) {
         // store the response return value (wrapper class insatance)  
         var result = a.getReturnValue();
         console.log('result ---->' + JSON.stringify(result));
         // set the component attributes value with wrapper class properties.   
         component.set("v.Accounts", result.accounts);
         component.set("v.page", result.page);
         component.set("v.total", result.total);
         component.set("v.pages", Math.ceil(result.total / recordToDisply));
      // enqueue the action 

// Apex Class

public   with sharing class DataTableWithPagenation {

 public static AccountPagerWrapper fetchAccount(Decimal pageNumber ,Integer recordToDisply) {
      Integer pageSize = recordToDisply;
      Integer offset = ((Integer)pageNumber - 1) * pageSize;
    // create a instance of wrapper class.
    AccountPagerWrapper obj =  new AccountPagerWrapper();
    // set the pageSize,Page(Number), total records and accounts List(using OFFSET)   
        obj.pageSize = pageSize;
        obj.page = (Integer) pageNumber;
        obj.total = [SELECT count() FROM account];
        obj.accounts = [SELECT Id, Name,Phone FROM Account ORDER BY Name LIMIT :recordToDisply OFFSET :offset];
    // return the wrapper class instance .
        return obj;
 // create a wrapper class with @AuraEnabled Properties    
 public class AccountPagerWrapper {
    @AuraEnabled public Integer pageSize {get;set;}
    @AuraEnabled public Integer page {get;set;}
    @AuraEnabled public Integer total {get;set;}
    @AuraEnabled public List<Account> accounts {get;set;}

Please mark it as best answer if it helps you.

Thank You,
Ajay Dubedi
Nicky ChaureNicky Chaure
When I tried above code, got below error.
This page has an error. You might just need to refresh it. Unable to find action 'fetchAccount' on the controller of c:LightPagination Failing descriptor: {c:LightPagination}

Please let me know why this error is throwing and how to resolve it.
Devid JohnDevid John
This error is throwing because you didn't create apex controller or your function name inside the controller is not the same as you are calling from js controller. 
Salesforce CodesSalesforce Codes
Please try this sample Code