gatsby-awesome-pagination-infinite-scroll

Combines the incredible gatsby-awesome-pagination with infinite scroll to make your Gatsby sites even more engaging.

Quick start

Open gatsby-node.js and import:

import { paginate } from 'gatsby-awesome-pagination-infinite-scroll';

Then, use paginate() like so:

exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions;

  // Fetch your items (blog posts, categories, etc).
  const blogPosts = doSomeMagic();

  // Create your paginated pages
  paginate({
    createPage, // The Gatsby `createPage` function
    items: blogPosts, // An array of objects
    itemsPerPage: 10, // How many items you want per page
    pathPrefix: '/blog', // Creates pages like `/blog`, `/blog/2`, etc
    component: path.resolve('...'), // Just like `createPage()`
  })
}

Now in your page query you can use the pagination context like so:

export const pageQuery = graphql`
  query ($skip: Int!, $limit: Int!) {
    allMarkdownRemark(
      sort: { fields: [frontmatter___date], order: DESC }
      skip: $skip // This was added by the plugin
      limit: $limit // This was added by the plugin
    ) {
      ...
    }
  }
`

Then inside your component, you can link to next / previous pages, and so on:

const BlogIndex = (props) => {
  return (
    <div>
      {data.allMarkdownRemark.edges.map(edge => <PostItem item={edge.node}/>)}
      <div>
        {/* previousPageLink and nextPageLink were added by the plugin */ }
        <Link to={props.pageContext.previousPagePath}>Previous</Link>
        <Link to={props.pageContext.nextPagePath}>Next</Link>
      </div>
    </div>
  )
}

Then for infinite scroll, use the new useInfiniteScroll() hook, and draw your data from pageData.

const BlogIndex = (props) => {


  const ref = useRef();
  const { isLoading, hasMore, error, pageData, before, after } = useInfiniteScroll({ containerRef: ref, initialData: props.data, initialPageContext: props.pageContext });


  return (
    <div ref={ref}>
      {pageData.allMarkdownRemark.edges.map(edge => <PostItem item={edge.node}/>)}
      <div>
        {/* previousPageLink and nextPageLink were added by the plugin */ }
        <Link to={props.pageContext.previousPagePath}>Previous</Link>
        <Link to={props.pageContext.nextPagePath}>Next</Link>
      </div>
    </div>
  )
}

For a more detailed example, see docs/examples.md.

For details on using gatsby-awesome-pagination, see here.