Skip to content

Instantly share code, notes, and snippets.

@Tundesamson26
Created April 22, 2022 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tundesamson26/ccbf77369ce4c75433eb4d38a4d31501 to your computer and use it in GitHub Desktop.
Save Tundesamson26/ccbf77369ce4c75433eb4d38a4d31501 to your computer and use it in GitHub Desktop.
Blog Interface
import fs from "fs";
import path from "path";
import matter from "gray-matter";
import Head from "next/head";
import Post from "../components/Post";
import { sortByDate } from "../utils";
export default function Home({ posts }) {
return (
<div>
<Head>
<title>Dev Blog</title>
</Head>
<div className="posts">
{posts.map((post, index) => (
<Post key={index} post={post} />
))}
</div>
</div>
);
}
export async function getStaticProps() {
// Get files from the posts dir
const files = fs.readdirSync(path.join("posts"));
// Get slug and frontmatter from posts
const posts = files.map((filename) => {
// Create slug
const slug = filename.replace(".md", "");
// Get frontmatter
const markdownWithMeta = fs.readFileSync(
path.join("posts", filename),
"utf-8"
);
const { data: frontmatter } = matter(markdownWithMeta);
return {
slug,
frontmatter,
};
});
return {
props: {
posts: posts.sort(sortByDate),
},
};
}
import Link from "next/link";
export default function Post({ post }) {
return (
<div className="card">
<img src={post.frontmatter.cover_image} alt="" />
<div className="post-date">Posted on {post.frontmatter.date}</div>
<h3>{post.frontmatter.title}</h3>
<p>{post.frontmatter.excerpt}</p>
<Link href={`/blog/${post.slug}`}>
<a className="btn">Bookmark</a>
</Link>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment