#How to add pagination
2 messages · Page 1 of 1 (latest)
To add pagination to your blog posts in Astro, you can use the paginate() function provided by Astro. This function will automatically generate the array to return from getStaticPaths() that creates one URL for every page of the paginated collection. The page number will be passed as a param, and the page data will be passed as a page prop.
Here is an example of how you can use the paginate() function in your getStaticPaths():
export async function getStaticPaths({ paginate }) {
const allPosts = await getCollection('blog')
const sortedPosts = allPosts.sort(
(a, b) => new Date(b.date) - new Date(a.date)
);
// Return a paginated collection of paths for all posts
return paginate(sortedPosts, { pageSize: 5 })
}
// The page prop has everything that you need to render a single page in the collection.
const { page } = Astro.props
In this example, paginate() is used to paginate the allPosts array with a page size of 5. The page prop now contains everything you need to render a single page.
Please note that paginate() assumes a file name of [page].astro or [...page].astro. The page param becomes the page number in your URL. For example, /posts/[page].astro would generate the URLs /posts/1, /posts/2, /posts/3, etc.
For more information, you can refer to the Astro API Reference (https://docs.astro.build/en/reference/api-reference/#getstaticpaths).