Introduction
Lightning web components are custom HTML elements build using HTML and modern JavaScript.
Lightning Web Components uses core Web Components standards and provides only what’s necessary to perform well in browsers supported by Salesforce. Because it’s built on code that runs natively in browsers, Lightning Web Components is lightweight and delivers exceptional performance. Most of the code you write is standard JavaScript and HTML.
Advantages
- Fast
- Lightweight
- Better browser compatibility
- Better security
Data table
Today we gonna see the LWC data table with some custom features that Salesforce doesn't provide us i.e pagination and searching.
- How to implement LWC data table
<lightning-datatable
key-field="id"
data={dataToShow}
hide-checkbox-column
show-row-number-column
columns={columns}
onrowaction={handleRowAction}
default-sort-direction={defaultSortDirection}
sorted-direction={sortDirection}
sorted-by={sortedBy}
onsort={onHandleSort}></lightning-datatable>
- Now we are going to create columns for the data table
get columns() {
return [{
label: 'First Name',
fieldName: 'firstname',
sortable: true,
}, {},
{
label: 'Last Name',
fieldName: 'lastname',
sortable: true,
}, {},
{
label: 'Phone',
fieldName: 'Phone',
type: 'phone',
sortable: true,
}, {},
{
label: 'Date ',
fieldName: 'createdDate',
type: "date-local"
},
{
label: 'View Record',
initialWidth: 100,
type: "button-icon",
typeAttributes: {
iconName: 'utility:preview',
name: 'View',
title: 'View',
disabled: false,
variant: "bare"
}
}
];
}
As you can see at last I used button recently Salesforce launch this new features in the LWC datatable where a user can add button on the row with onrowaction attribute of the LWC datatable. Now we have created columns for our LWC datatable.
- Now we are defining some other properties which we used in our 'lightning:datatable' tag some properties are variables and some properties are functions, so right now we are defining only variables.
@track defaultSortDirection = 'asc';
@track sortDirection = 'asc';
@track sortedBy;
Datatable Preview

Let's begin the fun part of datatable with pagination and other custom features
Pagination
- Define these variables in your code
@track pageSizeDefault =
'10';
@track recordsPerPage = [{
label: 10,
value: '10'
},
{
label: 20,
value: '20'
},
{
label: 50,
value: '50'
},
{
label: 100,
value: '100'
}
];
@track totalPages;
@track currentPage = 0;
@track startRecordIndex = 0;
@track endRecordIndex = 0;
@track dataToShow;- After defining the variables you need to create this function.
setTablePagination() {
if (this.data.length > 0) {
let pageList = JSON.parse(JSON.stringify(this.data));
let newList = new Array();
this.currentPage = 0;
this.startRecordIndex = 0;
this.endRecordIndex = this.pageSizeDefault - 1;
for (let i = 0; i < this.pageSizeDefault; i++) {
if (this.data.length > i) {
newList.push(JSON.parse(JSON.stringify(pageList[i])));
}
}
this.dataToShow = newList;
console.log('records', this.dataToShow);
this.totalPages = Math.ceil(this.data.length / this.pageSizeDefault);
}
}
Whenever your table data is ready you need to call this function. This function will divide your data. After doing this we need to add lwc: buttons and Combobox on the page so a user can control the pagination easily.
<div class="slds-grid slds-wrap slds-m-around_xx-small">
<div class="slds-col slds-grid slds-size_1-of-1">
<div class="slds-col slds-col slds-size_2-of-12">
<lightning-combobox name="Records Size" label="Records Per Page"
value={pageSizeDefault} options={recordsPerPage} onchange={handlePageSize}>
value={pageSizeDefault} options={recordsPerPage} onchange={handlePageSize}></lightning-combobox>
</div>
<div class="slds-col slds-size_10-of-12 slds-p-top_large">
<div class="slds-clearfix">
<div class="slds-align_absolute-center">
<lightning-button label="" icon-name="utility:left"
onclick={previousHandler} disabled={disabledPrevious}
variant="base">
onclick={previousHandler} disabled={disabledPrevious}
variant="base"></lightning-button>
<span class="slds-m-left_x-small"> Showing page {getCurrentPage}
from {totalPages} pages </span>
<lightning-button label="" icon-name="utility:right"
class="slds-m-left_x-small" onclick={nextHandler}
disabled={disabledNext} variant="base">
class="slds-m-left_x-small" onclick={nextHandler}
disabled={disabledNext} variant="base"></lightning-button>
</div>
</div>
</div>
</div>
</div>

You can change the pagination UI according to your requirement. Now we are going to handle previous and next button functionality as well as change Record page size.
handlePageSize(event) {
this.pageSizeDefault = event.target.value;
this.totalPages =
Math.ceil(this.tableDatalength / this.pageSizeDefault);
this.startRecordIndex = 0;
this.endRecordIndex = this.pageSizeDefault - 1;
this.currentPage = 0;
this.recordPageSize();
}
/
/This function will handle and change the number of records showing on per page recordPageSize() {
let newList = new Array();
for (let i = 0; i < this.pageSizeDefault; i++) {
if (this.data.length > i) {
newList.push(JSON.parse(JSON.stringify(this.data[i])));
}
}
this.dataToShow = newList;
}
previousHandler() {
let counter = 0;
let newList = new Array();
for (let i = this.startRecordIndex - this.pageSizeDefault;
i < this.startRecordIndex; i++) {
if (i > -1) {
newList.push(JSON.parse(JSON.stringify(this.data[i])));
counter++;
} else {
this.startRecordIndex++;
}
}
this.dataToShow = newList;
this.startRecordIndex = this.startRecordIndex - counter;
this.endRecordIndex = this.endRecordIndex - counter;
this.currentPage--;
}
nextHandler() {
let counter = 0;
let newList = new Array();
let numberOfRec = parseInt(this.pageSizeDefault) +
parseInt(this.endRecordIndex) + 1;
for (let i = this.endRecordIndex + 1; i < numberOfRec; i++) {
if (this.data.length > i) {
newList.push(JSON.parse(JSON.stringify(this.data[i])));
}
counter++;
}
this.startRecordIndex = this.startRecordIndex + counter;
this.endRecordIndex = this.endRecordIndex + counter;
this.currentPage++;
this.dataToShow = newList;
}
get getCurrentPage() {
return this.currentPage + 1;
}
//This function will make previous button disabled if table is on the first page
get disabledPrevious() {
return this.startRecordIndex == 0 ? true : false;
}
//This function will make next button disabled if table is on the last page
get disabledNext() {
return this.currentPage + 1 == this.totalPages ? true : false;
}
Congrats you have completed pagination on LWC:datatable.At last but not least we need to implement sorting as well. I know Salesforce already provided code for sorting the data of Datatable but that code is a little buggy. That's why I am doing this to share a code for sorting which runs seamlessly.
onHandleSort(event) {
console.log('event.detail', event.detail);
const {
fieldName: sortedBy,
sortDirection
} = event.detail;
const cloneData = [...this.dataToShow];
console.log('cloneData', cloneData);
cloneData.sort(this.sortBy(sortedBy, sortDirection === 'asc' ? 1 : -1));
console.log('cloneData', cloneData);
this.dataToShow = cloneData;
this.sortDirection = sortDirection;
this.sortedBy = sortedBy;
}
sortBy(field, reverse, primer) {
const key = primer ?
function (x) {
return primer(x[field]);
} :
function (x) {
return x[field];
};
return function (a, b) {
return a = key(a) ? key(a) : '', b = key(b) ? key(b) : '', reverse * ((a > b) - (b > a));
};
}
//This function will handle row action of our datatable
handleRowAction(event) {
const row = event.detail.row;
console.log(row);
}
That's all from my side I'll hope you enjoyed this blog and learned something new today. If you facing any issue while implementing this pagination on the lwc:datatable. Please feel free to ask in the comments section or you can mail us on our Gmail id.
Thanks to everyone 😁!!