Gatsby Starter Blog pagination

September 29, 2021 · 3 min readLucian Ciobanu
Tags:ReactGatsby

Almost 10 months have passed since I've started this little project of learning in public but 28 (actually 29 if you count this one) posts later, I really needed to implement a pagination to it as the landing page was getting a bit out of hand.

The first aproach I thought of was to use graphQL with the skip and limit arguments but because the page I'm displaying is built in index.js, a couple of articles have pointed to the fact that Gatsby's pageContext cant be used this way so I went with transforming this Gatsby built in blog page to something more in the lines of React so I can put my JavaScript skills to work.

This here is the extra code I needed to add:

import PropTypes from 'prop-type'

class BlogIndex extend React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      location: props.location,
      posts: props.data.allMarkdownRemark.nodes,
      postsPerPage: 7
    }
    this.paginate = this.paginate.bind(this);
  }
  
  //added the render property
  render() {
    //and inside this property I'm using the previous logic to render the rows
  }
}
  
//important to describe BlogIndex's property types
BlogIndex.propTypes = {
  data: PropTypes.shape({
    site: PropTypes.object,
    allMarkdownRemark: PropTypes.object
  })
}

export default BlogIndex

//already existing graphQL query; just adding it for context to understand
//how my data is getting in props
export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
      nodes {
        excerpt
        fields {
          slug
        }
        frontmatter {
          date(formatString: "MMMM DD, YYYY")
          title
          description
        }
      }
    }
  }
`
  

That's it! from this point it was fairly straight forward to create the pagination you can see and use on this here blog.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery