마크다운 콘텐츠를 렌더링 하려면 remark 라이브러리를 사용하면 된다.
(npm install remark remark-html).
그리고 remark 사용을 위해 lib/posts.js를 업데이트해준다.
remark엔 await을 사용해야 하므로 getPostData에 async 키워드를 추가해 주었다.
import { remark } from 'remark';
import html from 'remark-html';
export async function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents);
// Use remark to convert markdown into HTML string
const processedContent = await remark()
.use(html)
.process(matterResult.content);
const contentHtml = processedContent.toString();
// Combine the data with the id and contentHtml
return {
id,
contentHtml,
...matterResult.data,
};
}
이는 getPostData를 호출할 때 await을 사용하도록 getStaticProps도 업데이트해야 함을 의미한다.
export async function getStaticProps({ params }) {
// Add the "await" keyword like this:
const postData = await getPostData(params.id);
return {
props: {
postData,
},
};
}
마지막으로, Post 컴포넌트를 업데이트하고 dangerouslySetInnerHTML을 사용하여 contentHtml을 렌더링 한다.
export default function Post({ postData }) {
return (
<Layout>
{postData.title}
<br />
{postData.id}
<br />
{postData.date}
<br />
<div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />
</Layout>
);
}
이제 아래 페이지를 방문해 보면 블로그 콘텐츠가 출력된다.
'개발 > Next.js' 카테고리의 다른 글
useSWR로 좋아요 기능 구현해보기 (0) | 2024.01.20 |
---|---|
[Docs] Post / Index 페이지 다듬기 (0) | 2023.05.12 |
[Docs]동적 라우트 - getStaticProps 구현 & 세부사항 (0) | 2023.05.10 |
[Docs] 동적 라우트 - getStaticPaths 구현 (0) | 2023.05.10 |
[Docs] 동적 라우트(Dynamic Routes) (0) | 2023.05.10 |