Metadata
-
Date
-
Tagged
-
Older post
-
Newer post
Pagination in GatsbyJS
A page that lists all your posts can get incredibly long as more posts are added.
Pagination offers a solution to that problem. You can break up that single, long page into multiple, smaller pages.
This article will show you how to add pagination to your GatsbyJS site.
Create listing pages
Create a new file in src/templates/
that will serve as a blueprint for every page that lists a few posts.
If you already have one, the current component you use to list all the posts can often fulfill this role.
Calculate the amount of pages you need to display all posts (numPages
), with postsPerPage
as a maximum amount of posts to display on a single page.
In gatsby-node.js
create that amount of pages with your template.
The path for each page will be /<number>
, with an exception for /1
, that page will use /
instead.
Get data to those listing pages
You can pass data to the pages you created via context
.
The context
object will be available in the created pages on the pageContext
prop in React. You will also be able to access the keys in your GraphQL query for those pages.
Query GraphQL for wanted posts
Use limit
and skip
to only fetch data for the posts you want to show.
Navigate to previous/next page
You can use currentPage
and numPages
to determine the routes to the previous/next page.
They also make it possible to only show those links if they exist.
Add numbering
Iterate over numPages
and output a number with the relevant link.
Example
As an example, I converted the standard gatsby-starter-blog (demo) to work with pagination. gatsby-paginated-blog (demo)