Adding Pagination to the Blog Listing

Filed under random on June 28, 2021

I added some pagination to the blog listing page, took maybe an hour or so. Kinda surprised I manged that.

Basically, I edited my gatsby-node to generate a new set of nodes depending on the posts it finds. I also removed my index.js page so I could use the same code everywhere. My node generation now looks like this

const blogPagesTemplate = path.resolve('./src/templates/blog-page.js')
const paginateLimit =  siteMetadata.paginateLimit
createPage({
  path: `/`,
  component: blogPagesTemplate,
  context: {
    skip: 0,
    limit: paginateLimit,
    pageNumber: 1,
  }
})
for (let i = 1; i*paginateLimit < posts.length; i ++) {
  createPage({
    path: `/blogs/${i + 1}`,
    component: blogPagesTemplate,
    context: {
      skip: i * paginateLimit,
      limit: paginateLimit,
      pageNumber: i+1,
    }
  })
}

While my updated GraphQL query looks like this

  query ListBlogEntries($skip: Int, $limit: Int) {
    site {
      siteMetadata {
        title
        paginateLimit
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }, limit: $limit, skip: $skip) {
      nodes {
        excerpt
        fields {
          slug
        }
        frontmatter {
          date(formatString: "MMMM DD, YYYY")
          title
          description
          tags
        }
      }
    }
  }

All in all, happy with the result. Was easier than I thought, and I’m glad I was able to bring it into a single component.


Stephen Gream

Written by Stephen Gream who lives and works in Melbourne, Australia. You should follow him on Minds