Astro has a paginate function to create pages. To make this work in a flawless manner, we have to define our file structure like this.
src/pages/blog/├── [slug].astro # Creates individual posts└── [...page].astro # Creates pages, like /blog/, /blog/2/, etc.This structure is important because:
[slug]will be matched first, so we don’t lose any posts.[...page]will catch other URLs for page generation.
In case you’re wondering, 404 pages will still work because slugs and pages are generated during build time.
Using Paginate
Astro’s paginate function is deceptively simple. You just need to grab it as an argument from getStaticPaths, and use it directly.
---import { processFiles } from '@splendidlabz/astro/content'import { getCollection } from 'astro:content'
export const prerender = true // optional if output is static
export async function getStaticPaths({ paginate }) { const files = await getCollection('blog') const posts = await processFiles(files) return paginate(posts, { pageSize: 10 })}
const { page } = Astro.props---pageSize here refers to the number of items to be included in a single page.
And the page object contains many variables. The ones that are most relevant to us are:
data— the items for this pagecurrentPage— the current page numberlastPage— the last page number (or total number of pages)page.url.*— links to thefirst,prev,next, andlastpages
Populating items on the page
You can use data to populate items for the page:
---// ...const { page } = Astro.props---
{ page.data.map(post => ( <article> <h1> <a href={`/blog/${post.data.slug}`}>{post.data.title}</a> </h1> <Markdown> {post.data.excerpt} </Markdown> </article> ))}The Pagination UI
Creating a pagination UI is the hard part, because there’s really a lot of code.
But I’ve chosen to simplify it for us by building a Pagination component.
All you have to do: set the base directory, pass in the page variable, and choose whether you want a simple or full pagination.
---import { Pagination } from '@splendidlabz/astro'// ...const { page } = Astro.props---
{/* Choose between simple or full */}<Pagination base="blog" {page} type="full" />Simple Pagination
Contains only the previous and next page linksFull Pagination
Contains everything you expect from a standard page-based pagination componentThese are relatively unstyled at the moment so feel free to add your styles! You can find more information about the Pagination component in the docs.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson