Below is an example of a pagination component implemented in Lightning Web Components (LWC) in Salesforce.
paginationComponent
<template>
<div class="pagination">
<lightning-button-group>
<template for:each={pages} for:item="page">
<lightning-button
key={page}
label={page}
variant={currentPage === page ? 'brand' : 'neutral'}
onclick={handlePageClick}
></lightning-button>
</template>
</lightning-button-group>
</div>
</template>
paginationComponent:
import { LightningElement, api } from 'lwc';
export default class PaginationComponent extends LightningElement {
@api currentPage;
@api totalRecords;
@api recordsPerPage;
get pages() {
const pageCount = Math.ceil(this.totalRecords / this.recordsPerPage);
return Array.from({ length: pageCount }, (_, i) => i + 1);
}
handlePageClick(event) {
const selectedPage = parseInt(event.target.label, 10);
if (selectedPage !== this.currentPage) {
this.dispatchEvent(new CustomEvent('pagechange', { detail: selectedPage }));
}
}
}
In the above code, the paginationComponent accepts the following properties:
- currentPage: Represents the currently selected page.
- totalRecords: Indicates the total number of records available.
- recordsPerPage: Specifies the number of records to be displayed per page.
The pages getter calculates the total number of pages based on the provided properties. It creates an array of page numbers using the Array.from() method.
The handlePageClick method is invoked when a page button is clicked. It dispatches a custom event named pagechange with the selected page as the event detail.
To use the paginationComponent, include it in your parent component and handle the pagechange event to update the current page accordingly.
Example usage in parentComponent:
<template>
<div>
<!-- Display your records here based on the current page -->
</div>
<c-pagination-component
current-page={currentPage}
total-records={totalRecords}
records-per-page={recordsPerPage}
onpagechange={handlePageChange}
></c-pagination-component>
</template>
parentComponent:
import { LightningElement, track } from 'lwc';
export default class ParentComponent extends LightningElement {
@track currentPage = 1;
totalRecords = 50; // Example value, replace with your actual total records count
recordsPerPage = 10; // Example value, replace with the desired records per page
handlePageChange(event) {
this.currentPage = event.detail;
// Fetch the data for the new page based on the currentPage value
}
}
In the above example, the parent component includes the paginationComponent and handles the 'pagechange' event by updating the currentPage property. You can fetch the relevant data for the new page based on the currentPage value.
Remember to replace the example values with your actual data and customize the implementation as per your requirements.
That's it! You now have a pagination component implemented in Lightning Web Components (LWC) for Salesforce.