Day17 - Astro Series: Pagination

A beautiful gradient background with a title: "Pagination"

Introduction

Generating routes dynamically from content collections is convenient, but when items grow you need a way to display them in batches. Astro’s built-in pagination can help us implement this feature.

Define the problem

const students = [
{
student: 'Alice',
},
{
student: 'Bob',
},
{
student: 'Charlie',
},
{
student: 'Diana',
},
{
student: 'Evan',
},
];

Assume we have this student data. How can we use Astro’s pagination to produce 3 pages with 2 items per page? Example result:

  • First page - Alice, Bob
  • Second page - Charlie, Diana
  • Third page - Evan
  • …and so on

Using Pagination

With Astro’s built-in pagination, simply destructure the paginate function in the getStaticPaths return and include the data and options when returning.

---
// 1. Destructure and include the paginate function
export async function getStaticPaths({ paginate }) {
// 2. Define the data
const students = [{
student: 'Alice'
}, {
student: 'Bob'
}, {
student: 'Charlie'
}, {
student: 'Diana'
}, {
student: 'Evan'
}];
// 3. Return paginate with the data and configuration
return paginate(students, { pageSize: 2 });
}
// 4. All information for that page will be passed into Astro.props.page
const { page } = Astro.props;
---
<!-- Display the current page position -->
<h1>Page {page.currentPage}</h1>
<ul>
<!-- Display student information for each page -->
{page.data.map(({ student }) => <li>{student}</li>)}
</ul>

Understanding the page Prop

When using the pagination function, each page receives a prop named page that contains many useful pieces of information, such as:

interface Page<T = any> {
/** Results */
data: T[];
/** Metadata */
/** Count of the first item on the page, starting from 0. */
start: number;
/** Count of the last item on the page, starting from 0 */
end: number;
/** Total count of results */
total: number;
/** Current page number, starting from 1 */
currentPage: number;
/** Number of items per page (default is 25) */
size: number;
/** Number of the last page */
lastPage: number;
url: {
/** Link to the current page */
current: string;
/** Link to the previous page (if any) */
prev: string | undefined;
/** Link to the next page (if any) */
next: string | undefined;
};
}

Conclusion

This chapter showed how to use Astro’s built-in function to create pagination. It’s recommended to consider pagination once your site actually has a large amount of content.

Finally, it’s recommended to practice hands-on. If you run into issues, check out my example🔗:

  • Try adding pagination
  • Try separating the pagination into a component

Further reading