Skip to content

Instantly share code, notes, and snippets.

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 sagar-gavhane/6db48928eb55b49333726ec82dea3407 to your computer and use it in GitHub Desktop.
Save sagar-gavhane/6db48928eb55b49333726ec82dea3407 to your computer and use it in GitHub Desktop.
Building a blog with Next.js: [Slug].jsx
// file: pages/blog/[slug].js
import React from "react";
function BlogPostPage(props) {
return (
<div>
<h1>{props.blog.title}</h1>
<section dangerouslySetInnerHTML={{ __html: props.blog.content }}></section>
</div>
);
}
// pass props to BlogPostPage component
export async function getStaticProps(context) {
const fs = require("fs");
const html = require("remark-html");
const highlight = require("remark-highlight.js");
const unified = require("unified");
const markdown = require("remark-parse");
const matter = require("gray-matter");
const slug = context.params.slug; // get slug from params
const path = `${process.cwd()}/contents/${slug}.md`;
// read file content and store into rawContent variable
const rawContent = fs.readFileSync(path, {
encoding: "utf-8",
});
const { data, content } = matter(rawContent); // pass rawContent to gray-matter to get data and content
const result = await unified()
.use(markdown)
.use(highlight) // highlight code block
.use(html)
.process(content); // pass content to process
return {
props: {
blog: {
...data,
content: result.toString(),
}
},
};
}
// generate HTML paths at build time
export async function getStaticPaths(context) {
const fs = require("fs");
const path = `${process.cwd()}/contents`;
const files = fs.readdirSync(path, "utf-8");
const markdownFileNames = files
.filter((fn) => fn.endsWith(".md"))
.map((fn) => fn.replace(".md", ""));
return {
paths: markdownFileNames.map((fileName) => {
return {
params: {
slug: fileName,
},
};
}),
fallback: false,
};
}
export default BlogPostPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment