all posts

Gatsby: Paging Tags and Posts in Categories, Part 3

Published to Blog on 12 Mar 2018

Gatsby

This is the third post of three explaining how I implemented paged posts and tags by category on this Gatsby site using gatsby-pagination. In Part 1 I showed most of the structure of gatsby-node.js and how to create pages using Gatsby’s createPage action creator and gatsby-pagination’s createPaginationPages function. In Part 2 I showed the category and tag templates.

The only thing remaining is the component(s) used to render the paging functionality. Nothing ground-breaking here but for completeness sake I thought I would share it.

Pagination Component

class Pagination extends React.Component {
  render() {
    const defaults = {
      page: 0,
      pages: 0,
      prev: 0,
      next: 0,
      total: 0,
      prevText: '<< Previous',
      nextText: 'Next >>'
    };
    const myProps = _.merge({}, defaults, this.props);
    if (myProps.pages > 1) {
      return (
        <nav className="pagination">
          <div className="pagination__content">
            <PaginationLink
              className="pagination__newerposts"
              url={myProps.prev}
              text={myProps.prevText}
            />
            <span className="pagination__pagenumber">
              Page { myProps.page } of { myProps.pages }
            </span>
            <PaginationLink
              className="pagination__olderposts"
              url={myProps.next}
              text={myProps.nextText}
            />
          </div>
        </nav>
      );
    }
    return null;
  }
}

export default Pagination;
class PaginationLink extends React.Component {
  render() {
    if (this.props.url) {
      let className = 'nav-link';
      if (this.props.className) {
        className = `${className} ${this.props.className}`;
      }

      // clone this.props and then delete Component specific props
      // so we can spread the rest into the Link
      const { url, text, ...rest } = this.props;
      delete rest.style;
      delete rest.className;
      delete rest.text;
      delete rest.url;

      return (
        <GatsbyLink to={url} {...rest} className={className}>
          { text }
        </GatsbyLink>
      );
    }
    return null;
  }
}

export default PaginationLink;

Hopefully you found this series of posts helpful if you decide to take on paging posts, pages or tags in Gatsby. If you have any questions give me a shout on Twitter (@danhounshell) or use the Disqus comments below.


Dan Hounshell
Web geek, nerd, amateur maker. Likes: apis, node, motorcycles, sports, chickens, watches, food, Nashville, Savannah, Cincinnati and family.
Dan Hounshell on Twitter