Skip to content

Instantly share code, notes, and snippets.

@conormcafee
Created August 6, 2019 21:52
Show Gist options
  • Save conormcafee/d298204d07ddb3771a2dc84126395b4e to your computer and use it in GitHub Desktop.
Save conormcafee/d298204d07ddb3771a2dc84126395b4e to your computer and use it in GitHub Desktop.
I ran into the scenario this evening needing to show previous/next on 2 different templates on a Gatsby JS project. There is a solution to do this in the gatsby-node.js file but this relies on you having a flat structure - ie just a blog. My project renders different templates based on a category specified in the frontmatter which meant that my …
import React from "react"
import { StaticQuery, graphql, Link } from "gatsby"
import styled from "styled-components"
import { Flex } from "@rebass/grid"
const PrevNext = props => {
const { data, slug, category } = props
const getAllPages = data.allMarkdownRemark.edges
const pages = getAllPages
.filter(page => page.node.frontmatter.category === category)
.sort((a, b) =>
a.node.frontmatter.title > b.node.frontmatter.title
? 1
: b.node.frontmatter.title > a.node.frontmatter.title
? -1
: 0
)
const activePage = pages.findIndex(page => page.node.fields.slug === slug)
const prev = activePage !== 0
const next = activePage < pages.length - 1
return (
<Buttons
as="ul"
alignItems="center"
justifyContent="center"
px={[3, 4]}
py={[3, 4]}
mt={0}
>
{prev && (
<Button type="previous" to={pages[activePage - 1].node.fields.slug}>
<SubHeading>Prev</SubHeading>
<Title>{pages[activePage - 1].node.frontmatter.title}</Title>
</Button>
)}
{next && (
<Button type="next" to={pages[activePage + 1].node.fields.slug}>
<SubHeading>Next</SubHeading>
<Title>{pages[activePage + 1].node.frontmatter.title}</Title>
</Button>
)}
</Buttons>
)
}
export default props => {
return (
<StaticQuery
query={query}
render={data => (
<PrevNext data={data} slug={props.slug} category={props.category} />
)}
/>
)
}
const query = graphql`
query {
allMarkdownRemark(
sort: { order: ASC, fields: [frontmatter___title] }
limit: 1000
) {
edges {
node {
fields {
slug
}
frontmatter {
title
category
}
}
}
}
}
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment