Last active
June 1, 2020 05:59
-
-
Save sagar-gavhane/6db48928eb55b49333726ec82dea3407 to your computer and use it in GitHub Desktop.
Building a blog with Next.js: [Slug].jsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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