How to sort next.js blog posts by date

Published on Thursday, 9 June 2022

Recently, I added a new article to my blog and quickly realised the blog post list was sorted alphabetically. I wanted the blog posts with the most recent date at the top instead of having the post sorted alphabetically. In this article, I share how to sort your blog posts by the most recent date.

Convert the date string to a date object

To sort the blog post by date, we need to convert the date string variable to a Date Object.

Every blog post has a date string included in the post’s Front Matter.

Manually writing code that converts a date string to a Javascript Date object can be difficult and time-consuming, I used Luxon to simplify the process.

Luxon is an npm library that simplifies working with dates and times in JavaScript.

install Luxon

1npm install Luxon
2

Import it into the component file that renders your blog post list.

/components/postList/postList.js

1import { dateTime } from 'Luxon'
2

The dateTime.fromFormat() converts the date string to a Javascript Date Object.

fromFormat() is a function that creates a DateTime from a text string( date string), and fmt(the format the string is expected to be in) parsers the input string using a date format we pass in as a second parameter.

fromFormat() takes two arguments, a date string and a format string.

DateTime.fromFormat('09-06-2022, 'm-d-yyyy')

This will format the date string into a date object that looks like 06-09-2022.

I fetch the date string variable from the date included in every blog post's Front Matter.

Example of the date string included in the Front Matter in the blog post markdown file.

front-matter

With this date format mm-dd-yyyy, the post list will be sorted by the most recent month => day => year. This way, the blog post with the most recent month, day, and year stays at the top of the post list.

when I tested using the date format (dd-mm-yyyy), I did not get the desired result with the sort function.

Order blog post by most recent date

Now that the date string has been converted to a Javascript Date object, use the javascript built-in sort function to sort the blog posts in descending order.

In the src folder, go to the component displaying your blog post list, create a variable sortBlogPostsByDatesort and assign the sort function code to the variable

/components/postLists/postLists.js

1const sortBlogPostsByDate = posts.sort((a, b) => {
2    const beforeDate = DateTime.fromFormat(a.frontmatter.date, 'm-d-yyyy')
3    const afterDate = DateTime.fromFormat(b.frontmatter.date, 'm-d-yyyy')
4    return afterDate - beforeDate
5  })
6

The new Array data sortBlogPostsByDate contains the sorted blog posts with the most recent article displayed at the top of the list.

Finally using a javascript map function, loop through the sorted post data to display the blog posts list on the dom.

/components/postLists/postLists.js

1return (
2    <div className="postlist">
3      {posts &&
4
5        sortBlogPostsByDate.map((post) => {
6
7          return (
8            <DivList key={post.slug}>
9            
10              <Link href={{ pathname: `/${post.slug}` }}>
11                <PostTitle href={`/${post.slug}`}>
12                  {post.frontmatter.title}
13                </PostTitle>
14              </Link>
15
16              <PostData>
17                <PostTag>{post.frontmatter.tags}</PostTag>
18                <PostDate className="post-date">
19                  {post.frontmatter.date}
20                </PostDate>
21              </PostData>
22
23              <PostText>{post.frontmatter.description}</PostText>
24
25            </DivList>
26          )
27        })}
28    </div>
29  )
30

Your Blog post list should be sorted now, with the most recent post at the top of the list.

Final Result!

Final result

Discuss on Medium

Recommended Reads

Articles written by Kelechi Ogbonna. All rights reserved

Built with NextJs Typescript and TailwindCSS