1

I'm working on a blog in Next.js and MDX. For this, I downloaded this repo which I'm trying to adapt. But I can't find how I can sort the posts. For now they are with alphabetical order, but I would like to sort them by date (or a custom sort). How can I do this?

This is the code:

{posts.map((post) => (
    <section key={post.filePath}>
        <Link
            as={`/posts/${post.filePath.replace(/\.mdx?$/, "")}`}
            href={`/posts/[slug]`}
        >
            <a>{post.data.title}</a>
        </Link>
    </section>
))}
export function getStaticProps() {
    const posts = postFilePaths.map((filePath) => {
        const source = fs.readFileSync(path.join(POSTS_PATH, filePath));
        const { content, data } = matter(source);

        return {
            content,
            data,
            filePath,
        };
    });

    return { props: { posts } };
}

EDIT:

I tried to sort the map of elements. It worked, but every time I do a reload of the page it goes back to alphabetical order. From where this can come from?

This is my new code:

const SortedPosts = posts.sort((a, b) =>
    a.position > b.position ? 1 : -1
);
{SortedPosts.map((post) => (
    <section key={post.filePath} position={post.data.position}>
        <Link
            as={`/posts/${post.filePath.replace(/\.mdx?$/, "")}`}
            href={`/posts/[slug]`}
        >
            <a>{post.data.title}</a>
        </Link>
    </section>
))}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
JulSeb42
  • 393
  • 3
  • 12

2 Answers2

1

You don't need to create a separate variable for SortedPosts, you can simply sort the existing array of posts in-place using the sort function before returning it in getStaticProps()

export function getStaticProps() {
    const posts = postFilePaths.map((filePath) => {
    // existing code
    });

    posts.sort((a, b) => a.position > b.position ? 1 : -1 );
    return { props: { posts } };
}

TIP: if you'd like to reverse the order, you can simply swap -1 and 1 for eg: from 1 : -1 to -1 : 1


Reference: Check out this question which has more alternatives and details on sorting - Sort array of objects by string property value

Gangula
  • 5,193
  • 4
  • 30
  • 59
0

If you do not want to write the logic yourself, import a library such as lodash. After that, inside your getStaticProps function, before returning the posts do the following:

const sortedPosts = _.reverse(_.sortBy(posts, (post) => post.data.publishedOn))

return { props: { posts: sortedPosts } }
Aquib
  • 145
  • 1
  • 11