Pursuit of Loot

Adding Next and Previous post navigation

Posted on 15th January 2020

Tags:

Another quick win for the site today, inspired by the awesome people on Twitter who are putting in the work for the #100DaysOfGatsby challenge.

I noticed a lot of people have "next post" and "previous post" navigation on their articles, and until such a time where I add tags and categories, and some smart way of grouping my post data together to make clever recommendations, this will have to suffice as a way of pushing my banal content onto any reader foolish enough to reach the end of an article!

All it required was a couple of tweaks to the gatsby-node.js file in the section where we created our page slugs and voilà!

Before

result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/templates/post.js`),
context: {
slug: node.fields.slug,
}
});
});

After

const posts = result.data.allMarkdownRemark.edges;
posts.forEach(({ node }, index) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/templates/post.js`),
context: {
slug: node.fields.slug,
next: index === 0 ? null : posts[index - 1].node,
prev: index === posts.length - 1 ? null : posts[index + 1].node
}
});
});

One thing to note if you're going to implement this yourself - if your post query is sorted in DESCENDING order, your next and previous posts will be the opposite way around to how I've got mine.

Hope that helps, now go read one of my other articles using the links below 😁


Enjoyed this post? Feel free to share it with your audience using the links below:

Don't see your favourite social network on the list? Feel free to let me know and I'll get it added.

Comments

©2022 Pursuit of Loot. All rights reserved.