https://webkul.com/blog/magento2-create-list-with-pager-in-frontend/
So first you have to check where you are getting collection. Most of time its coming from block and this blog also share how to do it when collection is coming from block.
Now go to your block file and add a _prepareLayout() function. This function render the layout of page as its visible from its name like we can set page title and other things also this function runs automatically.
See below function.
protected function _prepareLayout()
{
parent::_prepareLayout();
$this->pageConfig->getTitle()->set(__('My Reward History'));
// Assuming $macAddress is available, get records for the given MAC address
$blockss_c = $this->getLayout()->createBlock('\Motoris\Vehiclelookup\Block\Cookie');
$macAddress = $blockss_c->get('customer_veh');
$records = $this->getRecordsByGarage($macAddress);
// Use $records to set up your layout
if ($records) {
// Create a unique pager block ID using a counter
$pagerId = 'reward_history_pager_' . self::$pagerCounter++;
// Create pager block using $records
$pager = $this->getLayout()->createBlock(
'Magento\Theme\Block\Html\Pager',
$pagerId
)->setAvailableLimit(array(3=>3,10=>10,15=>15,20=>20))
->setShowPerPage(true)->setCollection(
$records
);
$this->setChild($pagerId, $pager);
$records->load();
}
return $this;
}
See this line $records = $this->getRecordsByGarage($macAddress); which get collection, here we have pass a paremeter which is optional that really depend on your code.
Now we have to define a block progrmatically which name will come from $pagerId = 'reward_history_pager_' . self::$pagerCounter++; and this code set the child block.
$this->setChild($pagerId, $pager);
So we have define and set a child block. So far so good.
Now create a function
public function getPagerHtml()
{
// Retrieve the unique pager block ID dynamically
$pagerId = 'reward_history_pager_' . (self::$pagerCounter - 1);
// Return the HTML of the pager block with the unique ID
return $this->getChildHtml($pagerId);
}
$pagerId = 'reward_history_pager_' . (self::$pagerCounter - 1); You can make any name here as long as its unique.
Go to you phtml file and get this function to show pager on frontent
<?php if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom">
<?php echo $block->getPagerHtml(); ?>
</div>
<?php endif; ?>
Flush Cache and pager is on frontend. That's it. ):