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>
))}