Blogs usually have a previous and a next navigation on an article page. This allows the reader to read more if they are interested in the content.
There is a very simple way to populate this previous and next navigation, and I’m going to show you how. (This method works for other collections too).
Gathering previous and next posts
We already have a list of the published articles in getStaticPaths. So we just need to let the current page know:
- What’s the current post
- What’s the previous post
- What’s the next post
We can do that easily with indexes!
---export async function getStaticPaths() { const files = await getCollection('blog') const posts = await processFiles(files)
return posts.map((post, index) => { const prev = posts[index + 1] const next = posts[index - 1] // ... })}---In this case:
previs the next item on the list because we have sorted the posts in reverse order. Hence[index + 1]nextis the previous item on the list, hence[index - 1].
Then we pass the relevant posts into the props:
---export async function getStaticPaths() { // ... return posts.map((post, index) => { // ... return { params: { slug: post.data.slug }, props: { posts: { current: post, prev, next, }, }, } })}---We can now get the previous and next article from Astro.props.
---export async function getStaticPaths() { /* ... */ }
const { posts } = Astro.propsconst { current: post, prev, next } = posts---The next step is to detect whether the previous post or next post exists, and output the markup accordingly. For this, I prefer to put the logic in a PrevNextNav component.
We’re also going to pass the directory (blog in this case) into the component so the component can use this base to create the right link.
---// ...const { current: post, prev, next } = posts---
<PrevNextNav base="blog" {prev} {next}/>The previous/next component
What we do in this component is really easy. We just need to check if prev or next exists and output markup accordingly.
---import { If } from '@splendidlabz/astro'const { base = 'blog', prev, next } = Astro.props---
<div class="prev-next-nav"> <If condition={prev}> <a href={`/${base}/${prev?.data.slug}`}> <span> Prev: </span> <span>{prev?.data.title}</span> </a> </If>
<If condition={next}> <a href={`/${base}/${next?.data.slug}`}> <span> Next: </span> <span>{next?.data.title}</span> </a> </If></div>That’s it! The rest are just styles.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson